为什么我的集合中的元素没有被删除?

Why doesn't the element in my set get removed?

本文关键字:删除 元素 我的 集合 为什么      更新时间:2023-10-16
map<int,int> distance;
map<int,int> previous;
map<int,int>::iterator distIt;
map<int,int>::iterator prevIt;
set<int> nodes;
[..removed..]
it = topo.begin();
while(it != topo.end())
{
    distance[it->first] = 9999;
    previous[it->first] = 9999;
    nodes.insert(it->first);
    cout << "Processed: " << it->first << endl;
    it++;
}
distance[source] = 0;
while(!nodes.empty())
{
    distIt = min_element(distance.begin(), distance.end());
    int node = distIt->first;
    cout << "MIN: " << distIt->first << "|wtih cost|" << distIt->second << endl;
    nodes.erase(node);
    cin.get();
}
我得到的输出是:
Processed: 1
Processed: 1
Processed: 2
Processed: 2
Processed: 2
Processed: 3
Processed: 4
Processed: 4
Processed: 5
Processed: 5
MIN: 1|wtih cost|0
MIN: 1|wtih cost|0
MIN: 1|wtih cost|0

那么,为什么这里不能用erase(node)呢?

编辑:

SSCCE: http://ideone.com/EQ7BHt

在while循环中查找distance中的最小元素,然后擦除nodes中找到的键。擦除不会改变distance,因为它是一个完全不同的容器。因此,下一个循环传递将给您distance中的相同元素,并且erasenodes的调用将不起作用,因为您已经第一次删除了该数字。

换句话说:您必须删除从distance中找到的元素,否则您将始终找到相同的最小值,并且永远无法从nodes中删除其余元素。

使用node.delete(node)再试一次