29

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

Milad Khajavi
  • 2,769
  • 9
  • 41
  • 66

5 Answers5

52

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

Nawaz
  • 353,942
  • 115
  • 666
  • 851
Alok Save
  • 202,538
  • 53
  • 430
  • 533
7

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.

alestanis
  • 21,519
  • 4
  • 48
  • 67
5

Like interval in mathematics, stl uses [begin, end).

That's why we could write for (auto it = v.begin(); it != v.end(); ++it)

lostyzd
  • 4,515
  • 3
  • 19
  • 33
  • 1
    Yes! 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
3

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.
Tony The Lion
  • 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
2

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.

programmerjake
  • 1,794
  • 11
  • 15
VNarasimhaM
  • 1,460
  • 3
  • 22
  • 36