如何使用运算符取消谓词函数!在C ++? [英] How to negate a predicate function using operator ! in C++?

查看:87
本文介绍了如何使用运算符取消谓词函数!在C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要擦除所有不符合条件的元素。例如:删除字符串中不是数字的所有字符。我的解决方案使用boost :: is_digit工作得很好。

I want to erase all the elements that do not satisfy a criterion. For example: delete all the characters in a string that are not digit. My solution using boost::is_digit worked well.

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

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

Then I tried my own version, the compiler complained :( error C2675: unary '!' : 'my_is_digit' does not define this operator or a conversion to a type acceptable to the predefined operator

我可以使用not1但是我仍然认为操作符!在我的当前上下文中更有意义我如何实现这样的!像boost :: is_digit()?任何想法?

I could use not1() adapter, however I still think the operator ! is more meaningful in my current context. How could I implement such a ! like boost::is_digit() ? Any idea?

更新

按照Charles Bailey的说明,我编译了此代码段,但输出结果为空:

Follow Charles Bailey's instruction, I got this code snippet compiled, however the output is nothing:

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

有什么想法吗?

感谢,

Chan

Thanks,
Chan

推荐答案

您应该可以使用 std :: not1

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

为了这个工作你必须 #include< ; function> ,并从实用程序类 std :: unary_function< code>导出 my_is_digit char,bool> 。这完全是一个typedef助手,并且不会为你的函数添加运行时开销。

For this to work you have to #include <functional> and derive your my_is_digit functor from the utility class std::unary_function< char, bool >. This is purely a typedef helper and adds no runtime overhead to your functor.

完成工作示例:

#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;
}

这篇关于如何使用运算符取消谓词函数!在C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆