将std :: find_if与std :: string一起使用

时间:2009-04-20 12:10:18

标签: c++ stl

我在这里很傻但是在迭代字符串时我无法获得谓词的函数签名:

bool func( char );

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

在这个例子中谷歌并不是我的朋友:(有人在这里吗?

2 个答案:

答案 0 :(得分:11)

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

答案 1 :(得分:4)

如果您试图在std :: string c中找到单个字符str,则可以使用std::find()而不是std::find_if()。而且,实际上,您最好使用std::string的成员函数string::find()而不是<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;
}
相关问题