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

前端 未结 11 1789
半阙折子戏
半阙折子戏 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:40

    Here is your answer, directly from The Holy Standard:

    23.2.4.2 A vector satisfies all of the requirements of a container and of a reversible container (given in two tables in 23.1) and of a sequence, including most of the optional sequence requirements (23.1.1).
    23.1.1.12 Table 68 expressiona.pop_back() return typevoid operational semanticsa.erase(--a.end()) containervector, list, deque

    Notice that a.pop_back is equivalent to a.erase(--a.end()). Looking at vector's specifics on erase:

    23.2.4.3.3 - iterator erase(iterator position) - effects - Invalidates all the iterators and references after the point of the erase

    Therefore, once you call pop_back, any iterators to the previously final element (which now no longer exists) are invalidated.

    Looking at your code, the problem is that when you remove the final element and the list becomes empty, you still increment it and walk off the end of the list.

提交回复
热议问题