从STL列表中删除项目 [英] Erasing items from an STL list

查看:143
本文介绍了从STL列表中删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个函数,它将项目从一个STL列表移动到另一个,如果他们匹配某个条件。

I want to make a function which moves items from one STL list to another if they match a certain condition.

这段代码不是这样做的。迭代器很可能会被erase()函数无效并导致一个问题:

This code is not the way to do it. The iterator will most likely be invalidated by the erase() function and cause a problem:

for(std::list<MyClass>::iterator it = myList.begin(); it != myList.end(); it++)
{
  if(myCondition(*it))
  {
    myOtherList.push_back(*it);
    myList.erase(it);
  }
}

因此,任何人都可以提出更好的方法?

So can anyone suggest a better way to do this ?

推荐答案

擦除 返回一个迭代器指向删除后的元素:

Erase returns an iterator pointing to the element after the erased one:

std::list<MyClass>::iterator it = myList.begin();
while (it != myList.end())
{
  if(myCondition(*it))
  {
    myOtherList.push_back(*it);
    it = myList.erase(it);
  }
  else
  {
    ++it;
  }
}

这篇关于从STL列表中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆