Any one could explain me what is the meaning of past-the-end
. Why we call end()
function past-the-end?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
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.
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.The functions
begin()
andend()
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 reachedAdding another point to the above correct answers. This was also done to be compatible with arrays. For example in the code below:
This will work fine.
Instead if you had given :
it would miss sorting the last character.
This also helps to represent empty containers naturally.
Like interval in mathematics, stl uses
[begin, end)
.That's why we could write
for (auto it = v.begin(); it != v.end(); ++it)