计算机二级C语言中isdigit,C使用带字符串的标准算法,带有isdigit的count_if,函数转换...

博主正在尝试使用C++标准库的`count_if`算法来计算字符串中数字的个数,但遇到了编译错误。他们已经尝试了将`isdigit`函数指针转换为所需类型,但编译器仍然报错。他们不想创建适配器函数,而是寻求直接使用现有函数的方法,同时也对其他类似问题如检查字符串是否可打印、是否包含特定字符等表达了兴趣。博客探讨了如何在不使用lambda表达式的情况下在C++标准算法中使用函数指针。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

#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,但我找不到解决办法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值