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

梦想与她 提交于 2019-12-03 14:17:35

问题


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?


回答1:


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        |                      |
 |          |               |                      |
 +-------------------------------------------------+



回答2:


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)




回答3:


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

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




回答4:


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



来源:https://stackoverflow.com/questions/17796200/is-begin-end-for-any-empty-vector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!