您可以pop_back一个向量并仍然使用迭代器到最后一个元素吗? [英] Can you pop_back a vector and still use the iterator to the last element?

查看:89
本文介绍了您可以pop_back一个向量并仍然使用迭代器到最后一个元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如果在向量的最后一个元素上有一个迭代器并执行pop_back,会发生什么情况.

I wonder what happens if I have an iterator on the last element of the vector and do pop_back.

std::set<int> s;
s.insert(5);

std::vector<int> v = {1, 2, 3, 4, 5};

for (auto it = v.begin(); it != v.end();) {
    if (s.count(*it)) {
        std::swap(*it, v.back());
        v.pop_back();
    } else {
        ++it;
    }
}

上面的

上面的代码至少可以在clang上正常运行(v在该块之后是{1, 2, 3, 4}),但是检查it == v.end()是否使it无效是否正确?

Code above works properly (v is {1, 2, 3, 4} after that block) at least with clang, but is it correct to check if it == v.end() if it is invalidated?

推荐答案

您的直觉很好; vector::pop_back使迭代器和对最后一个元素的引用无效.如果it是这样的迭代器,则它将无效,因此无法与v.end()进行比较.

Your instincts are good; vector::pop_back invalidates iterators and references to the last element. If it is such an iterator, then it will be invalidated, and thus cannot be compared with v.end().

使用算法和擦除删除"习惯来解决此问题会更好:

It would be much better to fix this by using algorithms and the erase-remove idiom:

auto last_it = std::remove_if(v.begin(), v.end(), [&](const auto &val) {return s.count(val) != 0;});
v.erase(last_it, v.end());

这篇关于您可以pop_back一个向量并仍然使用迭代器到最后一个元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆