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

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

    pop_back() will only invalidate it if it was pointing to the last item in the vector. Your code will therefore fail whenever the last int in the vector is less than 10, as follows:

    *it = ints.back(); // Set *it to the value it already has
    ints.pop_back(); // Invalidate the iterator
    continue; // Loop round and access the invalid iterator

提交回复
热议问题