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

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

然后我尝试了我自己的版本,编译器提示:( error 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;
}

知道哪里出了问题吗?

谢谢,

最佳答案

您应该能够使用 std::not1 .

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

为此,您必须 #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;
}

关于c++ - 如何使用运算符来否定谓词函数!在 C++ 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4583310/

相关文章:

c++ - 无法在十六进制 C++ 中写入 x00

python - mac os 上的 cython 入门

c++ - 这是什么错误? (为什么它不出现在其他类中?)

c++ - 有没有办法在它以编程方式返回的引用上多次调用一个函数? -元组动态访问

c++ - 如何在c++中删除 vector 中的空格

c++ - 从两个容器中找到 'new' 项

c++ - 在不区分大小写的 std::map 中无法将 std::wstring 转换为 LPCTSTR

c++ - 如何创建节点结构类型的 Min STL priority_queue

c++ - 使用字符串和枚举映射时,Switch执行第一种情况而不是默认情况

c++ - 在 C++ 98 中优化 vector 过滤