Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Sep 22nd, 2004, 6:17 PM   #1
jasper_ferrer
Newbie
 
Join Date: Sep 2004
Posts: 23
Rep Power: 0 jasper_ferrer is on a distinguished road
hi, i have no problems iterating over a non-const vector. but when i make the vector conts , my program fails to compile.

is there really no way to iterate over a const vector?

tnx.
jasper_ferrer is offline   Reply With Quote
Old Sep 22nd, 2004, 7:36 PM   #2
Ashcroft
Programmer
 
Join Date: Sep 2004
Posts: 38
Rep Power: 0 Ashcroft is on a distinguished road
Hi,

You can iterate over a const vector with an const_iterator rather than an iterator.
Ashcroft is offline   Reply With Quote
Old Sep 23rd, 2004, 1:10 AM   #3
jasper_ferrer
Newbie
 
Join Date: Sep 2004
Posts: 23
Rep Power: 0 jasper_ferrer is on a distinguished road
that did it!

here's a sample code for those who might be interested:

#include <vector>
#include <iostream>

using std::vector;
using std::cout;

int main()
{
 int a[4] = {3, 8, 9, 1};

 const vector<int> v(a, a+4);

 for (vector<int>::const_iterator cit = v.begin(); cit != v.end(); cit++)
  cout << *cit << "\n";

 return 0;
}

many tnx, ashcroft!
jasper_ferrer is offline   Reply With Quote
Old Sep 23rd, 2004, 5:45 AM   #4
Ashcroft
Programmer
 
Join Date: Sep 2004
Posts: 38
Rep Power: 0 Ashcroft is on a distinguished road
Just an additional thing to be aware of when you use const_iterator, not all implementations define the operators correctly for const_iter. Sometimes code that needs to determine a relationship between an iterator and a const_iterator will fail with to compile with a fairly strange error. If you find yourself with such an implementation you can work around it by switching the order of the operands.

So if a comparison between a const_iterator and an iterator fails to compile then reverse the logic of the comparison and try again.

The other thing to be aware of (not that it would have affected your sample code) is that the insert and erase container functions expect an iterator and not a const_iterator.
Ashcroft is offline   Reply With Quote
Old Sep 23rd, 2004, 8:47 AM   #5
jasper_ferrer
Newbie
 
Join Date: Sep 2004
Posts: 23
Rep Power: 0 jasper_ferrer is on a distinguished road
i'll keep that in mind.
jasper_ferrer is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 12:17 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC