使用std::find_if和std::string

4

我在这里很愚蠢,但是我无法得到用于在字符串上迭代时查找find_if的谓词函数签名:

bool func( char );

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

在这种情况下,谷歌并没有给我带来帮助 :( 这里有人吗?
2个回答

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

是的,我知道我很愚蠢,我把find_if放在if语句中,无法解读错误消息,谢谢。 - Patrick

4

如果您想在std::string str中查找单个字符c,您可以使用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;
}

1
谢谢,但这不是我想做的:我正在重构一个isNumeric函数。 - Patrick

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接