Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the past-the-end iterator in STL C++?

Tags:

Any one could explain me what is the meaning of past-the-end. Why we call end() function past-the-end?

like image 510
Milad Khajavi Avatar asked Mar 06 '13 15:03

Milad Khajavi


People also ask

What is a past-the-end iterator?

std::vector::end Returns an iterator referring to the past-the-end element in the vector container. The past-the-end element is the theoretical element that would follow the last element in the vector. It does not point to any element, and thus shall not be dereferenced.

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 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.

Does iterator end point to the last element?

The end function returns whatever you'd get if you took an iterator to the last element in the list and incremented it or, for an empty list, returns the same thing begin returns.


1 Answers

The functions begin() and end() define a half open range([begin, end)), which means:
The range includes first element but excludes the last element. Hence, the name past the end.

enter image description here

The advantage of an half open range is:

  1. It avoids special handling for empty ranges. For empty ranges, begin() is equal to end() .

  2. It makes the end criterion simple for loops that iterate over the elements: The loops simply continue as long as end() is not reached

like image 85
Alok Save Avatar answered Sep 24 '22 18:09

Alok Save