I am moving an iterator
backward and forwards through a vector
.
I can check if the iterator ran off the end like so:
++my_iterator;
if ( my_iterator == my_vector.end() )
{
--my_iterator; // if I want to stop the iterator at the end.
my_iterator = my_vector.begin(); // if I want the iterator to wraparound.
}
But how do I check if it ran off the beginning?
Edit: So can I do this?
--my_iterator;
if ( my_iterator == my_vector.rend() )
{
my_iterator = my_vector.begin(); // if I want to stop the iterator at the beginning.
my_iterator = --(my_vector.rbegin()); // if I want the iterator to wraparound.
}
Or do I have to do this?
std::vector< T >::iterator temp_reverse_iterator = reverse_iterator< T >( my_iterator );
++temp_reverse_iterator;
if ( temp_reverse_iterator == my_vector.rend() )
{
my_iterator = my_vector.begin(); // if I want to stop the iterator at the beginning.
my_iterator = --(my_vector.end()); // if I want the iterator to wraparound.
}
else
{
my_iterator = temp_reverse_iterator.base(); // do I need to -- this?
}
And are both of these examples logically sound?