我目前正在编写一个程序,该程序在所述程序的某个点使用列表,我想遍历 3 个三个列表 a、b 和 c,并删除 b 和 c 中出现在 a 中的任何元素。我是这样做的:
//remove elements from OpenList that are in ClosedList
for(list<Node> :: iterator cloIt = ClosedList.begin(); cloIt != ClosedList.end(); cloIt++)
{
for(list<Node> :: iterator opIt = OpenList.begin(); opIt != OpenList.end(); opIt++)
{
for(list<Node> :: iterator neigIt = Neighbour.begin(); neigIt != Neighbour.end(); neigIt++)
{
if (*cloIt == *opIt)
{
opIt = OpenList.erase(opIt);
}
if (*cloIt == *neigIt)
{
neigIt = Neighbour.erase(neigIt);
}
}
}
}
然而,这导致我得到一个“List iterator not incrementable”错误 我该如何解决这个问题?
最佳答案
从你的删除调用中,你想要
- remove OpenList items if they are found in ClosedList list
- remove Neighbour items if they are found from ClosedListlist
最好将代码分成两个循环,而不是嵌套循环,例如:
1.如果在 ClosedList 列表中找到 OpenList 项,则删除它们
for(auto cloIt = ClosedList.begin(); cloIt != ClosedList.end(); ++cloIt)
{
OpenList.remove_if([&](const Node& n){ return n == *colIt; } );
}
2.如果从 ClosedLiSTList 中找到 Neighbor 项,则删除它们
for(auto cloIt = ClosedList.begin(); cloIt != ClosedList.end(); ++cloIt)
{
Neighbour.remove_if([&](const Node& n){ return n == *colIt; } );
}
很明显以前的代码是重复的,你可以为此编写一个通用函数:
void RemoveItem(std::list<Node>& node_list, std::list<Node>& node_list2)
{
for(auto cloIt = node_list2.begin(); cloIt != node_list2.end(); ++cloIt)
{
node_list.remove_if([&](const Node& n){ return n == *colIt; } );
}
}
现在你可以调用:
RemoveItem(OpenList, CloseList);
RemoveItem(Neighbour, CloseList);
更新: 不要忘记为节点类型定义 operator== ,例如,如果节点有 getId 接口(interface):
bool operator==(const Node& lhs, const Node& rhs)
{
return lhs.getId() == rhs.getId();
}
关于c++ - 使用列表语法中的删除更正迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16316899/