Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erasing items from an STL list

Tags:

c++

stl

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 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 ?

like image 936
Adam Pierce Avatar asked Feb 02 '09 01:02

Adam Pierce


People also ask

How do I clear a list in STL?

list::clear() is an inbuilt function in C++ STL which is declared in header file. list::clear(), clears the whole list. In other words the clear() removes all the elements present in the list container and leaves the container with size 0.

How do I remove an item from a list?

There are three ways in which you can Remove elements from List: Using the remove() method. Using the list object's pop() method. Using the del operator.

How do I remove multiple elements from a list in C++?

In general, the way to remove elements from a list based depending on a condition is to use the std::list::remove_if member function.


2 Answers

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;
  }
}
like image 108
sth Avatar answered Sep 20 '22 06:09

sth


STL lists have an interesting feature: the splice() method lets you destructively move elements from one list to another.

splice() operates in constant time, and doesn't copy the elements or perform any free store allocations/deallocations. Note that both lists must be of the same type, and they must be separate list instances (not two references to the same list).

Here's an example of how you could use splice():

for(std::list<MyClass>::iterator it = myList.begin(); it != myList.end(); ) {
    if(myCondition(*it)) {
        std::list<MyClass>::iterator oldIt = it++;
        myOtherList.splice(myOtherList.end(), myList, oldIt);
    } else {
        ++it;
    }
}
like image 40
bk1e Avatar answered Sep 20 '22 06:09

bk1e