Erasing items from an STL list

前端 未结 6 1850
北恋
北恋 2021-02-02 13:21

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

This code is not the way to do it. The iterator will most lik

6条回答
  •  别那么骄傲
    2021-02-02 13:43

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

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

提交回复
热议问题