C++ 将remove_if转换为remove_not_if
如何反转谓词的返回值,并删除返回false而不是true的元素 这是我的密码:C++ 将remove_if转换为remove_not_if,c++,stl,predicates,remove-if,C++,Stl,Predicates,Remove If,如何反转谓词的返回值,并删除返回false而不是true的元素 这是我的密码: headerList.remove_if(FindName(name)); (请忽略缺少擦除) FindName是一个简单的函子: struct FindName { CString m_NameToFind; FindInspectionNames(const CString &nameToFind) { m_NameToFind = nameToFind;
headerList.remove_if(FindName(name));
(请忽略缺少擦除)
FindName是一个简单的函子:
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;
}
};
我想要一些像:
list.remove_if(FindName(name) == false);
遗憾的是,还没有使用c++0x,所以不允许使用lambdas。我希望有比编写NotFindName函子更好的解决方案。不幸的是,我认为编写NotFindName函子是最好的选择。请查看
标题:
headerList.remove_if( std::not1( FindName( name ) ) );
哦,还有这个:
if(header.Name == m_NameToFind)
{
return true;
}
return false;
请不要那样做
return ( header.Name == m_NameToFind );
这更好,不是吗?或者,您可以使用boost绑定,这样就不必编写一元函数结构:
bool header_has_name (const CHeader& h, const CString& n) {return h.name == n;}
headerList.remove_if (boost::bind (header_has_name, _1, "name"));
如果没有,则删除\u:
headerList.remove_if (!boost::bind (header_has_name, _1, "name"));
您甚至可以使用std::equal()来完全避免使用header_has_name函数,但此时它会变得有点难看。谢谢,它可以与以下mods一起使用:Functor需要从std::unary_函数继承操作符()需要是const成员函数继承不是必需的,但是您需要定义它免费提供给您的正确typedef。至于
常数
-ness,不用说:)