Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove elements with specific value from std::list

Tags:

c++

list

stl

I need to remove elements with specific value from std::list. With the list<int> I used remove() method.

Now I have list<CMyClass> so I thought I should use remove_if() but it's predicate takes only one paramater - the element to be tested.

How do I write a function foo(const CMyClass &Bad) which removes from list all the elements equal to Bad?

Thanks

PS

struct CMyClass {
    void *Ptr;
    int Var;
}

bool is_equal(const CMyClass &A, const CMyClass &B)
{
    if (A.Ptr == B.Prt and A.Var == B.Var)
        return true;
    else
        return false;
}
like image 870
jackhab Avatar asked Mar 24 '09 15:03

jackhab


1 Answers

Your class has to implement operator == in your ClassName

bool operator == ( const Class& rhs );

and then you can use

list.remove( Bad )

If it is reasonable to your class to have operator == ( not just for remove ) - than list::remove is good for you solution. If operator == only for list::remove than it is better to use remove_if.

In the following example list::remove and list::remove_if is demonstrated.

struct Class
{
    int a_;
    int b_;

    Class( int a, int b ):
        a_( a ),
        b_( b )
    {}

    bool operator == (const Class &rhs)
    {
        return (rhs.a_ == a_ && rhs.b_ == b_);
    }

    void print()
    {
        std::cout << a_ << " " << b_ << std::endl;
    }
};

bool isEqual( Class lhs, Class rhs )
{
    return (rhs.a_ == lhs.a_ && rhs.b_ == lhs.b_);
}

struct IsEqual
{
    IsEqual( const Class& value ):
        value_( value )
    {}

    bool operator() (const Class &rhs)
    {
        return (rhs.a_ == value_.a_ && rhs.b_ == value_.b_);
    }

    Class value_;
};

int main()
{
    std::list<Class> l;

    l.push_back( Class( 1, 3 ) );
    l.push_back( Class( 2, 5 ) );
    l.push_back( Class( 3, 5 ) );
    l.push_back( Class( 3, 8 ) );

    Class bad( 2, 5 );

    std::cout << "operator == " << std::endl;
    l.remove( bad );
    std::for_each( l.begin(), l.end(), std::mem_fun_ref( &Class::print ) );

    std::cout << "binary function predicat" << std::endl;
    l.push_back( Class( 2, 5 ) );
    l.remove_if( std::bind2nd( std::ptr_fun(isEqual), bad ) );
    std::for_each( l.begin(), l.end(), std::mem_fun_ref( &Class::print ) );


    std::cout << "functor predicat" << std::endl;
    l.push_back( Class( 2, 5 ) );
    l.remove_if( IsEqual( bad ) );
    std::for_each( l.begin(), l.end(), std::mem_fun_ref( &Class::print ) );

    return 0;
}
like image 50
Mykola Golubyev Avatar answered Oct 16 '22 00:10

Mykola Golubyev