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

- 2,769
- 9
- 41
- 66
5 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.
The advantage of an half open range is:
It avoids special handling for empty ranges. For empty ranges,
begin()
is equal toend()
.It makes the end criterion simple for loops that iterate over the elements: The loops simply continue as long as
end()
is not reached
-
The illustration smells like Josuttis :) – fredoverflow Mar 06 '13 at 16:30
-
1Not just `begin()` and `end()`; generally, `[begin, end)` defines a **sequence** of values, regardless of where the iterators come from or where the values are held. – Pete Becker Mar 06 '13 at 16:58
-
63. The number of elements in the range is `end - begin` (for random-access iterators), not some expression with an annoying +1 in it. – Steve Jessop Mar 06 '13 at 17:06
Because it doesn't point to the last element of a container, but to somewhere past the last element of a container.
If you dereference end()
it results in undefined behaviour.

- 21,519
- 4
- 48
- 67
Like interval in mathematics, stl uses [begin, end)
.
That's why we could write for (auto it = v.begin(); it != v.end(); ++it)

- 4,515
- 3
- 19
- 33
-
1Yes! The first answer that doesn't talk about containers, which are not required to create sequences. – Pete Becker Mar 06 '13 at 17:00
-
But so is `[begin,end]`; and then there also are `(a,b]`, `(a,b)`. Please elaborate, what's so special that you see in math about the `[a,b)` compared to other intervals? – Hi-Angel Mar 25 '19 at 23:32
-
@Hi-Angel [Why numbering should start at zero](https://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html) – lostyzd Nov 21 '19 at 11:24
Literally, because it points one past the end of the array.
It is used because that element is empty, and can be iterated to, but not dereferenced.
int arry[] = {1, 2, 3, 4, /* end */ };
^^^^^^^
std::end(arry) would point here.

- 61,704
- 67
- 242
- 415
-
Not just arrays; the `end` iterator points past the end of the target sequence, regardless of where the the iterators come from or where the values are held. – Pete Becker Mar 06 '13 at 16:59
Adding another point to the above correct answers. This was also done to be compatible with arrays. For example in the code below:
char arr[5];
strcpy(arr, "eakgl");
sort(&arr[0], &arr[5]);
This will work fine.
Instead if you had given :
sort(&arr[0], &arr[4]);
it would miss sorting the last character.
This also helps to represent empty containers naturally.

- 1,794
- 11
- 15

- 1,460
- 3
- 22
- 36