c++ - 使用列表语法中的删除更正迭代

标签 c++

我目前正在编写一个程序,该程序在所述程序的某个点使用列表,我想遍历 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”错误 我该如何解决这个问题?

最佳答案

从你的删除调用中,你想要

  1. remove OpenList items if they are found in ClosedList list
  2. 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/

相关文章:

c++ - 在 Visual C++ 中称为 RGB 的类

c++ - 什么时候修改链表?

c++ - 运行时检查失败 #2 - bMatix 周围的堆栈已损坏

c++ - CLion 中 clang 格式的 RawStringFormats 错误

c++ - Release模式仍然依赖于 MSVCP110D.dll (C++ MSVS)

c++ - Qt DBus 没有接收到信号

C++11 与现有库/框架的兼容性

C++ vector 位置设置为 1 而不是 0

c# - CLI/C# 将 std::vector<> 结构数据传递给 C#

c++ - 如何将正则表达式 vector 与一个字符串匹配?