我想以最短的代码方式计算字符串中的所有数字。我这样试过:
#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/