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

前端 未结 11 1573
半阙折子戏
半阙折子戏 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 07:03

    pop_back() invalidates only iterators that point to the last element. From C++ Standard Library Reference:

    Inserting or removing elements invalidates references, pointers, and iterators that refer to the following element. If an insertion causes reallocation, it invalidates all references, iterators, and pointers.

    So to answer your question, no it does not invalidate all iterators.

    However, in your code example, it can invalidate it when it is pointing to the last element and the value is below 10. In which case Visual Studio debug STL will mark iterator as invalidated, and further check for it not being equal to end() will show an assert.

    If iterators are implemented as pure pointers (as they would in probably all non-debug STL vector cases), your code should just work. If iterators are more than pointers, then your code does not handle this case of removing the last element correctly.

提交回复
热议问题