Ivan Ivanov
Ivan Ivanov

Reputation: 61

Removing element from the standard list

Suppose I have the following class

class Human
 {
public:
    Human();
    Human(string,int);
    virtual ~Human();
    string getName();

protected:

private:
    string name;
    int staj;
 };

I have created list with 2 elements that I pushed in

  list<Human> mylist;
  Human x ("Mike",13);
  Human y("pavlek",33);

I am trying to remove if there is element with name "Mike",I tried removing it like this :

   for(list<Human>::iterator it=mylist.begin();it!=mylist.end();++it)
  {


  if(it->getName()=="Mike")
  {
      mylist.remove(it);
      cout<< "removed";
       cout<<it->getName();
  }

}

However I get error at passing the value to the remove() function,what should I exactly pass in order to delete this element from the list?

Upvotes: 0

Views: 60

Answers (2)

MSalters
MSalters

Reputation: 179779

Matheus Portela's solution was the old C++98 method. It's a lot easier now:

mylist.remove_if( [](Human const& h){return h.getName()=="Mike";} );

The condition here is [](Human const& h){return h.getName()=="Mike";}. That is a lambda expression which returns true if the Human h should be removed. You can test any other property or combination of properties there. The { } part of the lambda is a real function body; you could even have for-loops in there:

Other examples:

mylist.remove_if( [](Human const& h){return h.getName().size() > 4; } );

mylist.remove_if( [](Human const& h) {
     for (char c: h.getName())
         if (c=='i') return true; // remove if name contains an i
     return false; } );

Mind you, the latter would be easier with std::any_of.

Upvotes: 0

Matheus Portela
Matheus Portela

Reputation: 2460

You have simply mistaken erase and remove. According to the C++ reference, remove is used to remove from the list all elements whose values are equals to the given parameter. On the other hand, erase removes a single element given its position or a range of elements given the start and end positions.

If you only need to delete the first element containing "Mike" as its name, simply do something like this:

for(list<Human>::iterator it=mylist.begin();it!=mylist.end();++it)
{
    if(it->getName() == "Mike")
    {
        mylist.erase(it);
        break;
    }
}

Please notice that after using erase, your iterator will be invalidated. You can circumvent it by using the returned value of erase, which is the next valid iterator value. This detail is important if your list might contain multiple elements whose name is "Mike".

Upvotes: 2

Related Questions