C++ 使用带字符串的标准算法,带 isdigit 的 count_if,函数转换

标签 c++ string algorithm function casting

我想以最短的代码方式计算字符串中的所有数字。我这样试过:

#include <string>
#include <algorithm>

unsigned countNumbers(const std::string s) {
    return count_if(s.begin(), s.end(), isdigit);
}

错误信息是:

a.cc: In function ‘unsigned int countNumbers(std::string)’:
a.cc:5:45: error: no matching function for call to ‘count_if(std::basic_string<char>::const_iterator, std::basic_string<char>::const_iterator, <unresolved overloaded function type>)’
a.cc:5:45: note: candidate is:
/usr/include/c++/4.6/bits/stl_algo.h:4607:5: note: template<class _IIter, class _Predicate> typename std::iterator_traits<_InputIterator>::difference_type std::count_if(_IIter, _IIter, _Predicate)

我知道 count_if() 想要的功能如下: bool (* f)(字符);作为第三个参数,所以我尝试转换函数:

unsigned countNumbers(const std::string s) {
    return count_if(s.begin(), s.end(), reinterpret_cast<bool (*)( char )>(isdigit));
}

错误信息是:

a.cc: In function ‘unsigned int countNumbers(std::string)’:
a.cc:5:80: error: overloaded function with no contextual type information

我也尝试了更长一点的版本,它给出了同样的编译错误:

unsigned countNumbers(const std::string s) {
    typedef bool ( * f_ptr )( char );
    f_ptr ptr = reinterpret_cast<f_ptr>(isdigit);
    return count_if(s.begin(), s.end(), ptr);
}

我想避免的解决方案是创建一个适配器函数:

#include <string>
#include <algorithm>

bool is_digit(char c) {
    return isdigit(c);
}

unsigned countNumbers(const std::string s) {
    return count_if(s.begin(), s.end(), is_digit);
}

我的问题是如何在 std::algorithm 的函数中使用函数 int(*f)(int) 而无需创建适配器函数且不使用 lambda 表达式?

当我知道如何解决问题时,我有更多的问题可以解决,例如:

  • 检查字符串是否可打印:find_if_not(s.begin(), s.end(), isprint)
  • 检查字符串是否包含“,.!?...”:find_if (s.begin(), s.end(), ispunct) 还有更多...

我只是想知道如何通过 std::algorithms 在标准 C++ 中获得更多的字符串可能性 我在互联网上搜索了很长时间,我找到了similar problem , 但我没有找到解决方案

最佳答案

您可以使用静态转换来解析函数。或者,如果这是您想做的很多事情,您可以使用模板来解决它:

#include <string>
#include <cctype>
#include <algorithm>

unsigned count(const std::string& s) {
  return std::count_if(s.begin(), s.end(), static_cast<int(*)(int)>(std::isdigit));
}

template <int(*Pred)(int)> 
unsigned foo(const std::string& s) {
  return std::count_if(s.begin(), s.end(), Pred);
}

int main() {
  count("");
  foo<std::isdigit>("");
  foo<std::isprint>("");
}

static_cast 是解决歧义的“常规”方式 - 它总是按照您的预期进行,并且可以成为更大表达式的一部分。

关于C++ 使用带字符串的标准算法,带 isdigit 的 count_if,函数转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15039858/

相关文章:

mysql - 使用 MySQL 从字符串中分离电子邮件地址

c# - 如何拆分具有多个空格作为分隔符的字符串?

c - 在C中删除结构内部的字符串

c++ - 行为处理列表和标量实体的通用打印函数?

c++ - C++中的指针声明

c++ - 在编译时替换目标文件中的符号。例如换出 main

java - Math.log 背后的算法 - Java

java - 将 32 位整数中的所有位取反而产生错误输出的代码是什么?

algorithm - 构建切片树的算法是什么?

C++:将静态类成员与静态类成员的传递版本进行比较