Turning remove_if into remove_not_if
Asked Answered
I

3

6

How can I reverse a predicate's return value, and remove the elements that return false instead of true?

Here is my code:

headerList.remove_if(FindName(name));

(please ignore lack of erase)

with FindName a simple functor:

struct FindName
{
    CString m_NameToFind;

    FindInspectionNames(const CString &nameToFind)
    {
        m_NameToFind = nameToFind;
    }

    bool operator()(const CHeader &header)
    {
        if(header.Name == m_NameToFind)
        {
            return true;
        }

        return false;
    }
};

I would like something like:

list.remove_if(FindName(name) == false);

Not yet using c++0x, so lambdas not allowed, sadly. I'm hoping there is a nicer solution than writing a NotFindName functor.

Ibnrushd answered 5/10, 2010 at 14:27 Comment(0)
B
15

Check not1 in the <functional> header:

headerList.remove_if( std::not1( FindName( name ) ) );

Oh, and this:

if(header.Name == m_NameToFind)
{
    return true;
}

return false;

Please don't do that.

return ( header.Name == m_NameToFind );

That's much better, isn't it?

Bowery answered 5/10, 2010 at 14:31 Comment(2)
Thanks, it works with the following mods: Functor needs to inherit from std::unary_function<CHeader, bool> operator() needs to be a const member functionIbnrushd
Actually inheritance is not necessary, but you need to define the proper typedef that it gives you for free. As for the const-ness, it goes without saying :)Script
A
3

alternatively you could use boost bind so you don't have to write that unary_function struct:

bool header_has_name (const CHeader& h, const CString& n) {return h.name == n;}

headerList.remove_if (boost::bind (header_has_name, _1, "name"));

and for remove_if_not:

headerList.remove_if (!boost::bind (header_has_name, _1, "name"));

You could even use std::equal() to avoid the header_has_name function completely but at that point it becomes a little bit ugly.

Albumenize answered 5/10, 2010 at 15:42 Comment(0)
N
0

Unfortunately I think writing a NotFindName functor is your best bet.

Nevadanevai answered 5/10, 2010 at 14:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.