Consider following piece of code
void foo( bool forwad )
{
vector<MyObject>::iterator it, end_it;
int dir;
it = some_global_vector.begin() + some_position;
if( forward )
{
dir = 1;
it += 1;
end_it = some_global_vector.end();
}
else
{
dir = -1;
it -= 1;
end_it = some_global_vector.begin()-1;
}
while( it != end_it )
{
if( do_domething() )
break;
it += dir;
}
}
As you can see there is some doubt when forward == false
becouse there is an substraction from begin()
and iterator it
can be substracted when it points at begin()
. I can't find anywhere if it is ok until I not dereference this bad pointing iterator).
EDIT
I read ISO C++ Standard and have some conclusions.
There is no promise that vector::begin()
can't internaly point to memory at adress 0
, and I was thinking that It is the end, but all containers depend on standard alocator. This alocator depends on new
operator. And also, there is no information that new
will never return 0
. But standard alocator depends also on delete
operator and this operator is supose to do nothing if you pass 0
. So by this fact, new
can't return 0
becouse there will be no way to delete that pointer, and by that, non empty vector
can't return begin()
that points to 0
.
Conclusion:
If above is right decrementing interator that points at vector::begin()
should be safe, since internal memory of the vector
is continouse.
Am I right?
ULTIMATE ANSWER
Even if it works now and will be working in the future it is undefined behavour according to the standard. If you do this, you are doing this on your own risk. See this simmilar question for more informations.
See Question&Answers more detail:os