我想删除所有不满足条件的元素。例如:删除字符串中所有不是数字的字符。我使用 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/