我想遍历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/