Does pop_back() really invalidate *all* iterators on an std::vector?

前端 未结 11 1570
半阙折子戏
半阙折子戏 2021-01-05 06:26
std::vector ints;

// ... fill ints with random values

for(std::vector::iterator it = ints.begin(); it != ints.end(); )
{
    if(*it < 10)
         


        
11条回答
  •  别那么骄傲
    2021-01-05 06:47

    The "official specification" is the C++ Standard. If you don't have access to a copy of C++03, you can get the latest draft of C++0x from the Committee's website: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2723.pdf

    The "Operational Semantics" section of container requirements specifies that pop_back() is equivalent to { iterator i = end(); --i; erase(i); }. the [vector.modifiers] section for erase says "Effects: Invalidates iterators and references at or after the point of the erase."

    If you want the intuition argument, pop_back is no-fail (since destruction of value_types in standard containers are not allowed to throw exceptions), so it cannot do any copy or allocation (since they can throw), which means that you can guess that the iterator to the erased element and the end iterator are invalidated, but the remainder are not.

提交回复
热议问题