Is it allowed to increment an iterator variable it
that already is at end()
, i.e. auto it = v.end()
?
vector
?++it
maybe idempotent if it==v.end()
?I ask, because I stumbled upon code like this:
std::vector<int> v{ 1, 2, 3, 4, 5, 6, 7 };
// delete every other element
for(auto it=v.begin(); it<v.end(); ++it) { // it<end ok? ++it ok on end?
it = v.erase(it);
}
It works fine with g++-6, but that is no proof.
For one it<v.end()
may only work with vectors
, I suppose it should read it!=v.end()
in general. But in this example that would not recognize the end of v
if ++it
is applied when it already is on the end.
Obviously if the iterator is advanced past the last element inside the loop the comparison in the for-loop statement will evaluate to false and the loop will happily continue into undefined behaviour.
If iter is an InputIterator, you can use: ++iter and iter++ to increment it, i.e., advance the pointer to the next element. *iter to dereference it, i.e., get the element pointed to.
It appears that you can still decrement the iterator returned from end() and dereference the decremented iterator, as long as it's not a temporary.
In something like an std::vector the ::end() iterator will point to one past the last element. You can't dereference this iterator but you can compare it to another iterator. If you compare another iterator to end() you know you've reached the end of the container.
No the behaviour is undefined. You are allowed to set an iterator to end()
, but you must not increment it or dereference it.
You are allowed to decrement it so long as the backing container is not empty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With