【问题标题】:Finding an alphanumeric character in a string using find_if and isalnum使用 find_if 和 isalnum 在字符串中查找字母数字字符
【发布时间】:2012-10-27 01:54:32
【问题描述】:

我正在使用 g++ 4.7

我想做的是这个,

find_if(s.begin(), s.end(), isalnum);

其中isalnumcctype 中定义,s 是一个字符串。

logman.cpp:68:47: error: no matching function for call to ‘find_if(std::basic_string<char>::const_iterator, std::basic_string<char>::const_iterator, <unresolved overloaded function type>)’

但是,这行得通,

bool my_isalnum(int c) {
    return isalnum(c);
}

find_if(s.begin(), s.end(), my_isalnum);

如何在不创建自己的函数的情况下使其工作?

【问题讨论】:

  • 如果 C++11 适合您,您可以使用 lambda 表达式。

标签: c++ string stl g++


【解决方案1】:

这应该可以工作

#include <algorithm >
#include <cctype>

auto result = std::find_if(std::begin(s), std::end(s),  isalnum) ;

【讨论】:

    【解决方案2】:

    这应该可行。

    #include <algorithm>
    #include <cctype>
    auto result = std::find_if (begin(s), end(s), std::isalnum);
    

    【讨论】:

      【解决方案3】:

      编译器在消除 this functionthis function 之间的歧义时遇到问题。你想要第一个,你必须在这里帮助编译器,通过使用强制转换指定签名:

      find_if(s.begin(), s.end(), (int(*)(int))isalnum);
      

      【讨论】:

      • 请注意,添加范围解析运算符::isalnum 也可以。
      猜你喜欢
      • 2016-02-28
      • 2022-06-12
      • 1970-01-01
      • 1970-01-01
      • 2014-02-15
      • 2021-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多