Patrick
Patrick

Reputation: 8318

using std::find_if with std::string

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?

Upvotes: 5

Views: 14482

Answers (2)

John Dibling
John Dibling

Reputation: 101456

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

Upvotes: 4

anon
anon

Reputation:

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

Upvotes: 12

Related Questions