今天调了一天,终于解决了一个非常莫名奇妙的问题。大概可以描述如下:
set<int> nodes;
for(auto n: nodes)
{
//some code using n
if(condition)
nodes.erase(nodes.find(n));
}
本以为这可以逐个遍历,但情况是,当erase一次之后再遍历,n又会回到之前的一个node!
这大概是因为set是树状结构,删除一个节点之后的遍历不想我们想象的那样能顺序继续。
改成如下可以:
set<int> nodes;
set<int> record;
for(auto n: nodes)
{
//some code using n
if(record.find(n) != record.end())
continue;
if(condition)
nodes.erase(nodes.find(n));
else
record.insert(n);
}