我在这里很愚蠢,但是我无法得到用于在字符串上迭代时查找find_if的谓词函数签名:
bool func( char );
std::string str;
std::find_if( str.begin(), str.end(), func ) )
在这种情况下,谷歌并没有给我带来帮助 :( 这里有人吗?
#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";
}
}
如果您想在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;
}