Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it allowed to increment an end iterator?

Tags:

c++

iterator

Is it allowed to increment an iterator variable it that already is at end(), i.e. auto it = v.end()?

  • Is it allowed in general?
  • If not, is it not allowed for vector?
  • If yes, is ++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.

like image 243
towi Avatar asked Oct 02 '16 18:10

towi


People also ask

What happens if you increment the iterator past 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.

Can you increment an iterator C++?

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.

Can you decrement end iterator C++?

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.

What does the end iterator point to?

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.


1 Answers

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.

like image 53
Bathsheba Avatar answered Sep 24 '22 01:09

Bathsheba