Re: reverse_iterator problem
Massif wrote:
I've got a reverse_iterator going through a vector. It has to start at a
point somewhere in the middle of the vector, run backwards through it in a
circle until it reaches the point it started at.
The cut down version of the code is as follows:
vector<CMLSection*>::reverse_iterator
itBack; vector<CMLSection*>::reverse_iterator itMarkerBack;
itBack= find_if(m_Vect.rbegin(), m_Vect.rend(), IsMatch);
itMarkerBack= itBack;
do
{
if( itBack== m_Vect.rend() )
{
itBack= m_Vect.rbegin();
}
DoSomething(itBack);
}while( ++itBack!= itMarkerBack);
It's a bit more complicated than that - but you get the idea.
The problem is - when I'm in that if clause - i.e. the iterator is equal
to rend() then the iterator is still pointing to a valid address, and when
it gets set to rbegin() it no longer points to a valid address.
That understanding is wrong. rbegin() is dereferencable while rend() is not
(past the end), just like with begin() and end(). The very point of
reverse_iterators is that you can use them like their forward iterating
cousins, the _MUST_ be as exchangeable as possible.
BTW: I see another problem with your algorithm, and that is that it invokes
undefined behaviour when the vector is empty. If I were you, I'd go for the
most simple solution:
marker = find_if(...);
// from marker to end
for( iterator it = marker; it!=end; ++it)
do_something(*it);
// from beginning to marker
for( iterator it = begin; it!=marker; ++it)
do_something(*it);
Obviously, this lends itself to the use of std::for_each or std::transform
or, if you can come up with a good name, to encapsulation is a similar
algorithm itself.
Uli