std :: list erase不兼容的迭代器

use*_*rbb 2 c++ stl

我有对象列表.我从该列表中获取了一些项目并对项目执行了一些操作.如果工作没有错误,我希望从列表中删除这些项目.之后,在擦除时,我得到异常迭代器的异常.我知道tmp是不同的列表.但是如何解决这个问题呢?

#include <list>

class A
{
public:
    A(int i):i_(i){}
private:
    int i_;
};

int _tmain(int argc, _TCHAR* argv[])
{
    std::list<A> list;
    A a(1), b(2), c(3);
    list.push_back(a);
    list.push_back(b);
    list.push_back(c);

    std::list<A> tmp;
    tmp.insert(tmp.end(), list.begin(), list.end());
    // do something with tmp
    // if all is ok, then erase what is done
    list.erase(tmp.begin(), tmp.end());

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

tmp.Insert并不总是满满的list.它可以复制部分list,所以我不想要清楚整体list.

Dou*_* T. 6

您无法使用其他列表中的迭代器从一个列表中删除.迭代器"指向"列表中的某个节点.它指向特定列表中的某些内容.当您将这些内容复制到另一个列表中时,您现在有两个包含两组节点的列表.您的迭代器仅指向其中一个副本,而不是两者.

在程序中,std::list析构函数将使列表清理,因此您甚至不需要明确清除.

正如其他人所说,你可以使用clear来吹走列表中的内容.但我不是百分之百确定你的意思.你的意思是擦除列表中同样位于tmp的所有内容吗?如果是这种情况,那么您可能希望将remove_if与谓词一起使用

 class CIsContainedInOtherList
 { 
 private:
     const std::list<int>& m_list;
 public:
      CIsContainedInOtherList(const std::list<int>& list);

      // return true if val is in m_list
      bool operator()(const int& val) const
      {
          std::list<int>::const_iterator iter 
             = std::find(m_list.begin(), m_list.end(), val);
          return (iter != m_list.end())
      }
 }

 int main()
 {
      ...
      CIsContainedInOtherList ifInOtherList(tmp);
      std::list<int>::iterator iter = 
              remove_if(list.begin(), list.end(), ifInOtherList);
      // remove everything that matched the predicate
      list.erase(iter, list.end());
 }
Run Code Online (Sandbox Code Playgroud)