Any one could explain me what is the meaning of past-the-end
. Why we call end()
function past-the-end?
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.
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.
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.
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.
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.
The advantage of an half open range is:
It avoids special handling for empty ranges. For empty ranges, begin()
is equal to end()
.
It makes the end criterion simple for loops that iterate over the elements: The loops simply continue as long as end()
is not reached
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