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

发布于 2024-07-16 20:19:41 字数 184 浏览 6 评论 0原文

我在这里很愚蠢,但在迭代字符串时,我无法获得将要查找的谓词的函数签名:

bool func( char );

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

在这种情况下,谷歌不是我的朋友:(这里有人吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

败给现实 2024-07-23 20:19:41
#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";
    }
}
#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";
    }
}
書生途 2024-07-23 20:19:41

如果您试图在 std::string str 中查找单个字符 c ,您可能可以使用 std::find() 而不是比std::find_if()。 而且,实际上,您最好使用 std::string 的成员函数 string::find() 而不是 中的函数。

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

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文