我想以最短的代码方式计算字符串中的所有数字.我试过这样的方式:
#include
#include
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::const_iterator, std::basic_string::const_iterator, )’
a.cc:5:45: note: candidate is:
/usr/include/c++/4.6/bits/stl_algo.h:4607:5: note: template typename std::iterator_traits<_inputiterator>::difference_type std::count_if(_IIter, _IIter, _Predicate)
我知道count_if()想要的函数如下:
bool(* f)(char);作为第三个参数,所以我试图强制转换函数:
unsigned countNumbers(const std::string s) {
return count_if(s.begin(), s.end(), reinterpret_cast(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(isdigit);
return count_if(s.begin(), s.end(), ptr);
}
我想避免的解决方案是创建一个适配器的函数:
#include
#include
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),这些函数需要bool(* f)(int)而不创建适配器函数而不使用lambda表达式?
当我知道如何解决问题时,我会遇到更多问题,例如:
>检查字符串是否可打印:find_if_not(s.begin(),s.end(),isprint)
>检查字符串是否包含“,.!?…”:find_if(s.begin(),s.end(),ispunct)
和更多…
由于std :: algorithms,我只想知道如何在标准C中有更多的字符串可能性
我在互联网上搜索很长时间,我找到了similar problem,但我找不到解决办法