![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
Join Date: Sep 2004
Posts: 23
Rep Power: 0
![]() |
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. |
|
|
|
|
|
#2 |
|
Programmer
Join Date: Sep 2004
Posts: 38
Rep Power: 0
![]() |
Hi,
You can iterate over a const vector with an const_iterator rather than an iterator. |
|
|
|
|
|
#3 |
|
Newbie
Join Date: Sep 2004
Posts: 23
Rep Power: 0
![]() |
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! |
|
|
|
|
|
#4 |
|
Programmer
Join Date: Sep 2004
Posts: 38
Rep Power: 0
![]() |
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. |
|
|
|
|
|
#5 |
|
Newbie
Join Date: Sep 2004
Posts: 23
Rep Power: 0
![]() |
i'll keep that in mind.
|
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|