0

I would like to know how to remove an object from a list base on a condition.

After researching, this is what I got, but it still doesn't work!

So I would like to know how to use remove_if with erase.

Class A
{
public:
    A(int x,int y);
    int x;
    int y;
};


int main()
{
    list<A> listA;

    A lista1(123,32);
    listA.push_back(lista1);
    A lista2(3123,1233);
    listA.push_back(lista2);
    A lista3(123,4123);
    listA.push_back(lista3);

    //HERE HOW TO REMOVE LIST if x = 123?
    listA.erase(remove_if(listA.begin(),listA.end(),/*REMOVE CRITERIA*/);
}
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
mister
  • 3,303
  • 10
  • 31
  • 48

1 Answers1

7

std::list has a remove_if member function:

http://www.cplusplus.com/reference/stl/list/remove_if/

For your predicate you could either write a functor:

struct RemoveIfX
{
    RemoveIfX(int x) : m_x(x) {}

    bool operator() (const A& a)
    {
        return (a.x == m_x);
    }

    int m_x;
};

listA.remove_if(RemoveIfX(123));

Or use a lambda:

listA.remove_if([](const A& a) { return (a.x == 123); });
  • hi there, thanks for your reply! so are you saying i should overload my Class A operator()? – mister Nov 21 '11 at 23:59
  • 1
    No, RemoveIfX is a standalone helper class. Lambdas are generally preferred these days as they are more concise. I gave both options in case you were using a compiler with no support for them. –  Nov 22 '11 at 00:02
  • I would like to know more about the lambda method (I tried it but got only compiler errors with g++ 4.4.1). – Walter Nov 22 '11 at 00:04
  • I think it might have only been added from 4.5 onwards. There might be some useful general information for you here: http://msdn.microsoft.com/en-us/library/dd293608.aspx –  Nov 22 '11 at 00:14
  • @bleep this is awesome stuff. Unfortunately, it won't port to old versions of gcc (I'm writing code which is intended to be public). – Walter Nov 22 '11 at 00:20
  • 1
    The RemoveIfX version should work even with quite old versions of gcc. – Karl Knechtel Nov 22 '11 at 00:48