Is begin() == end() for any empty() vector?

C++Stdvector

C++ Problem Overview


I have long assumed that for any empty std::vector V, V.begin() == V.end(). Yet I see nothing in the C++ specification that states this to always be true. Is it necessarily true or does it just happen to be true on most implementations?

C++ Solutions


Solution 1 - C++

Yes, that's what the standard requires it to be for empty() for any container.

§ 23.2.1 Table 96 of the C++11 standard says:

 +----------+---------------+----------------------+
 |Expression|  Return Type  | Operational Semantics|
 |----------|---------------|----------------------|
 |a.empty() |Convertible    |a.begin() == a.end()  |
 |          |to bool        |                      |
 |          |               |                      |
 +-------------------------------------------------+

Solution 2 - C++

23.2.1 General container requirements, specifically Table 96 Container Requirements has

> a.empty() convertible to bool, operational semantics a.begin() == a.end()

Then

> 6 begin() returns an iterator referring to the first element in the container. end() returns an iterator which is the past-the-end value for the container. If the container is empty, then begin() == end();

(emphasis mine)

Solution 3 - C++

http://www.cplusplus.com/reference/vector/vector/end/

If the container is empty, end() is the same as begin().

Solution 4 - C++

Yes, that is true. Here is the proof. And, of course, std::distance(a.begin(), a.end()) == 0 for an empty vector.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOldPeculierView Question on Stackoverflow
Solution 1 - C++RapptzView Answer on Stackoverflow
Solution 2 - C++juanchopanzaView Answer on Stackoverflow
Solution 3 - C++JiminionView Answer on Stackoverflow
Solution 4 - C++Ivan SmirnovView Answer on Stackoverflow