tags:

views:

650

answers:

2

I'm being stupid here but I can't get the function signature for the predicate going to find_if when iterating over a string:

bool func( char );

std::string str;
std::find_if( str.begin(), str.end(), func ) )

In this instance google has not been my friend :( Is anyone here?

+5  A: 
#include <iostream>
#include <string>
#include <algorithm>

bool func( char c ) {
    return c == 'x';
}

int main() {
    std::string str ="abcxyz";;
    std::string::iterator it = std::find_if( str.begin(), str.end(), func );
    if ( it != str.end() ) {
     std::cout << "found\n";
    }
    else {
     std::cout << "not found\n";
    }
}
anon
Yep, knew I was being stupid, I had the find_if in an if statement and couldn't decipher the error message, thanks
Patrick
+5  A: 

If your're trying to find a single character c within a std::string str you can probably use std::find() rather than std::find_if(). And, actually, you would be better off using std::string's member function string::find() rather than the function from <algorithm>.

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
  std::string str = "abcxyz";
  size_t n = str.find('c');
  if( std::npos == n )
    cout << "Not found.";
  else
    cout << "Found at position " << n;
  return 0;
}
John Dibling
Thanks, but not what I was trying to do: I was refactoring an isNumeric function
Patrick