c++ - 有没有一种方法可以在删除和插入c++中的元素时循环遍历multiset或unordered_set中的元素

标签 c++ unordered-set multiset

我想遍历multiset或unordered_set中的每个元素,并且在循环期间,我可以插入和删除该元素。
例如:

unordere_set<int> myset = { 1, 2, 3, 4 };
for (auto it = myset.begin(); it != myset.end(); ++it) {
    myset.erase(*it);
    // do something that needs to use the set without *it like in a recursion function that takes the reference of the set
    myset.insert(*it);      
}
我不想创建该集合的副本,因为该集合可能很大,并且效率不是很高。

最佳答案

我看不到此代码有问题(不过未经测试)

unordered_set<int> myset = { 1, 2, 3, 4 };
for (auto it = myset.begin(); it != myset.end(); ) {
    auto save = *it;
    it = myset.erase(it);
    // do something that needs to use the set without *it like in a recursion function that takes the reference of the set
    myset.insert(save);      
}
我的推理是mysave.insert(save)不应使迭代器it无效,因为它不会引起对unordered_set的重新哈希处理,因为您所做的只是添加回先前删除的元素。但是当然,这确实取决于您对// do something ...所做的工作

关于c++ - 有没有一种方法可以在删除和插入c++中的元素时循环遍历multiset或unordered_set中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62650763/

相关文章:

c++ - 来自 std 的 unordered_set

c++ - 没有比较的多集?

C++:在多集容器中使用自己的类

c++ - 通过范围变量计算点周围的积分器 x 和 y 坐标

c++ - Eclipse (C/C++) 错误 : Job found still running after platform shutdown

c++ - 如何在 C++ 中直播网络摄像头服务器?

C++ 模板可变参数函数 undefined reference

c++ - unordered_set如何确定c++中的插入顺序?

c++ - Unordered_set 插入最坏情况

python - 添加计数器删除键