为什么我的集合中的元素没有被删除?
Why doesn't the element in my set get removed?
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
中的相同元素,并且erase
对nodes
的调用将不起作用,因为您已经第一次删除了该数字。
换句话说:您必须删除从distance
中找到的元素,否则您将始终找到相同的最小值,并且永远无法从nodes
中删除其余元素。
使用node.delete(node)
再试一次
相关文章:
- 如何从存储在std::映射中的std::集中删除元素
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 从矢量中删除元素后出现隔离错误
- 如何使用remove_if从矢量中删除元素
- 如何从使用 for 循环中的矢量大小的矢量中删除元素
- C++映射不删除元素
- 如何从标准::元组中删除元素?
- 在动态数组中添加/删除C++元素
- 如何通过比较彼此的成员从QStringList中删除元素
- 如何修复从矢量中删除元素的错误?
- 从 std::set 中删除元素,同时在 C++17 中迭代该元素
- 使用remove_if从矢量中删除元素
- 用C++从三维矢量中删除元素
- 从对象数组中删除元素
- 如何在不使用 vector::erase() 的情况下编写自定义 Vector 方法来删除元素?
- C++ - 按自定义数据类型向量的值删除元素
- 从任意容器中廉价删除元素的惯用方法?
- 从数组中删除元素不起作用的函数
- 删除元素 BST
- 从向量中删除元素时未处理的异常