Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ what's the result of iterator + integer when past-end-iterator?

suppose you have a random access iterator (eg of std::vector myVector)

when iter + someInt is past-end-iterator, iter + someInt == myVector.end() ??

or could it be different value than myVector.end() ?

like image 515
eugene Avatar asked May 10 '11 08:05

eugene


People also ask

What happens if you increment an 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.

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.

What is end () iterator?

The list::end() is a built-in function in C++ STL which is used to get an iterator to past the last element. By past the last element it is meant that the iterator returned by the end() function return an iterator to an element which follows the last element in the list container.

How do you get to the end of an iterator?

To get the last element in an iterator loop you can use std::next() (from C++11). The loop is generally terminated by iterator != container. end() , where end() returns an iterator that points to the past-the-end element.


2 Answers

It's undefined behaviour, the standard says nothing about the result of that.

like image 39
Xeo Avatar answered Oct 06 '22 09:10

Xeo


It's Undefined Behavior. Anything may happen. Just to name a few of the options: Nothing at all, program exits, exception, crash.

like image 167
MSalters Avatar answered Oct 06 '22 08:10

MSalters