简体   繁体   English

在remove_if中取反谓词

[英]Negate predicate in remove_if

I try to remove objects from a vector using vector::erase and std::remove_if. 我尝试使用vector :: erase和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. 不幸的是,此上下文当前不支持C ++ 11。

Thanks 谢谢

Use the std::not1 adapter to negate the value returned by your isValid function. 使用std::not1适配器取反isValid函数返回的值。 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. 请注意, std::not1需要一个函数对象 (C ++将该函数对象称为“ functor”),因此,如果您在名称空间中有一个普通函数,则还需要std::ptr_fun从函数中创建一个函数对象。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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