Rotate remove_if to remove_not_if

How to change the value of the returned predicate and remove elements that return false instead of true?

Here is my code:

headerList.remove_if(FindName(name)); 

(please ignore the lack of erasure)

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); 

C ++ 0x is not used yet, so lambdas is not allowed, unfortunately. I hope there is a nicer solution than writing the NotFindName functor.

+6
c ++ stl predicates remove-if
source share
3 answers

Mark 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, do not do that.

 return ( header.Name == m_NameToFind ); 

This is much better, right?

+15
source share

alternatively you can use boost bind, so you do not need to write this unary_function structure:

 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 can even use std :: equal () to completely avoid the header_has_name function, but at this point it gets a little ugly.

+3
source share

Unfortunately, I think creating a better NotFindName functor is a better choice.

0
source share

All Articles