简体   繁体   中英

Negate predicate in remove_if

I try to remove objects from a vector using vector::erase and std::remove_if. I have an external namespace which does the selection ala:

template<unsigned int value, someType collection>
bool Namespace::isValid(const Foo* object){

   do something
}

Now I have a vector which contains some element which I want to filter if the are valid. In order to do so I do:

 std::vector<foo*> myVector;
 //fill it
 myVector.erase( std::remove_if(myVector.begin(), myVector.end(), Namespace::isValid<myValue, myCollectionType>), myVector.end());

Now this works fine and removes all valid candidates, but actually I want to keep and remove all other. Hence, I need to negate the predicate. Is there any way to do so? Unfortunately, C++11 is not currently supported in this context.

Thanks

Use the std::not1 adapter to negate the value returned by your isValid function. Note that std::not1 expects a function object (C++ calls this a "functor"), so if you have a plain function in a name space you will also need std::ptr_fun to create a function object out of your function.

So,

myVector.erase( std::remove_if( myVector.begin(),
                                myVector.end(),
                                Namespace::isValid<myValue, myCollectionType> ),
                myVector.end() );

becomes

myVector.erase( std::remove_if( myVector.begin(),
                                myVector.end(),
                                std::not1( std::ptr_fun( Namespace::isValid<myValue, myCollectionType> ) ) ),
                myVector.end() );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM