How to negate a predicate function using operator ! in C++?

Posted by Chan on Stack Overflow See other posts from Stack Overflow or by Chan
Published on 2011-01-03T09:21:38Z Indexed on 2011/01/03 9:53 UTC
Read the original article Hit count: 177

Filed under:
|

Hi,

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

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

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?

Thanks,
Chan Nguyen

© Stack Overflow or respective owner

Related posts about c++

Related posts about stl