Re: reverse_iterator and const_reverse_iterator
Roland Pibinger wrote:
On Sun, 17 Jun 2007 06:45:56 -0700, Jess wrote:
I think the two reverse_iterators are the same, except that the const_
version doesn't allow me to change the value pointed to by the
iterators. However, I have a program that works for reverse_iterator
but not const_reverse_iterator:
for(vector<int>::const_reverse_iterator i = v.rbegin(); i != v.rend();
++i)
cout << (*i) << endl;
This one fails, with error
no match for 'operator!=' in 'i != std::vector<_Tp, _Alloc>::rend()
[with _Tp = int, _Alloc = std::allocator<int>]()'
I guess your compiler cannot distinguish between the const and the
non-const rend(). Try:
Seems like it does distinguish between them, and calls the non-const
version on a non-const vector. The problem arises from comparing a
const_iterator to a plain iterator.
for(vector<int>::const_reverse_iterator i = v.rbegin();
i != ((const std::vector<int>) v).rend();
i != ((const std::vector<int>&) v).rend();
That's a minor typo, but critical. As written, it copies the vector,
creating an iterator that points into the copy rather than the original.
A simpler way of doing this, if you have a library that conforms to the
not-yet-official C++0x standard, is to call crbegin() and crend()
instead of rbegin() and rend(). crbegin() and crend() return const
iterators.
--
-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)