繁体   English   中英

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

[英]using std::find_if with std::string

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM