如何使用运算符否定谓词函数!在C++中?

Cha*_*han 4 c++ stl

我想擦除所有不符合标准的元素.例如:删除字符串中不是数字的所有字符.我使用boost :: is_digit的解决方案效果很好.

struct my_is_digit {
 bool operator()( char c ) const {
  return c >= '0' && c <= '9';
 }
};

int main() {
 string s( "1a2b3c4d" );
 s.erase( remove_if( s.begin(), s.end(), !boost::is_digit() ), s.end() );
 s.erase( remove_if( s.begin(), s.end(), !my_is_digit() ), s.end() );
 cout << s << endl; 
 return 0;
}
Run Code Online (Sandbox Code Playgroud)

然后我尝试了自己的版本,编译器抱怨:(错误C2675:一元'!':'my_is_digit'没有定义此运算符或转换为预定义运算符可接受的类型

我可以使用not1()适配器,但我仍然认为运算符!在我目前的背景下更有意义.我怎么能实现这样的!喜欢boost :: is_digit()?任何的想法?

更新

按照Charles Bailey的指示,我编译了这段代码片段,但输出结果是什么:

struct my_is_digit : std::unary_function<bool, char> {
    bool operator()( char c ) const {
        return isdigit( c );
    }
};

std::unary_negate<my_is_digit> operator !( const my_is_digit& rhs ) {
    return std::not1( rhs );
}

int main() {
    string s( "1a2b3c4d" );
    //s.erase( remove_if( s.begin(), s.end(), !boost::is_digit() ), s.end() );
    s.erase( remove_if( s.begin(), s.end(), !my_is_digit() ), s.end() );
    cout << s << endl;  
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

知道什么是错的吗?

谢谢,

CB *_*ley 11

你应该可以使用std::not1.

std::unary_negate<my_is_digit> operator!( const my_is_digit& x )
{
    return std::not1( x );
}
Run Code Online (Sandbox Code Playgroud)

为此,您必须从实用程序类#include <functional>派生并派生您的my_is_digit仿函数std::unary_function< char, bool >.这纯粹是一个typedef帮助器,并没有为你的仿函数增加运行时开销.


完整的工作示例:

#include <string>
#include <algorithm>
#include <functional>
#include <iostream>
#include <ostream>

struct my_is_digit : std::unary_function<char, bool>
{
    bool operator()(char c) const
    {
        return c >= '0' && c <= '9';
    }
};

std::unary_negate<my_is_digit> operator!( const my_is_digit& x )
{
    return std::not1( x );
}

int main() {
    std::string s( "1a2b3c4d" );
    s.erase( std::remove_if( s.begin(), s.end(), !my_is_digit() ), s.end() );
    std::cout << s << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)