【发布时间】:2012-09-21 13:53:45
【问题描述】:
假设你有一个
std::unordered_set<std::shared_ptr<A>> as;
// (there is an std::hash<std::shared_ptr<A>> specialisation)
并且你想在迭代时替换它的一些元素:
for (auto it = as.begin(); it != as.end(); ++it) {
if ((*it)->condition()) {
as.erase(it);
as.insert(std::make_shared<A>(**it));
}
}
这可能会使erase 和insert 处的迭代器无效(如果发生重新散列),因此此循环将表现出未定义的行为,并且很可能会严重崩溃。
我能想到的一个解决方案是使用两个单独的 vectors 来缓冲 insert 和 erase 操作,然后使用采用迭代器对进行擦除和插入的重载(这可能对重新散列更友好)。
即使我使用缓冲区方法,这仍然看起来臃肿的代码,并可能导致可能都不必要的两次重新散列。
那么,有没有更好的方法呢?
【问题讨论】:
标签: c++ iterator replace unordered-set