对c++ 标准库中算法传递参数

本文介绍了一种使用C++标准库函数count_if的方法来统计字符串数组中特定长度以上的字符串数量,并提供了两种改进方案:通过函数对象和模板参数实现更灵活的长度判断。

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

考虑这个问题:

// 字符串数组中长度大于3的有多少个?
char* c_str[] = {"abc", "dfhso", "237498", "jdwre"};

你可以想到这样办:

#include <cstdio> // strlen
#include <algorithm> // count_if
using namespace std;
bool lengthThan3(const char* c)
{
	return strlen(c) > 3;
}
int main()
{
	// 字符串数组中长度大于3的有多少个?
	char* c_str[] = {"abc", "dfhso", "237498", "jdwre"};
	int length = sizeof(c_str) / sizeof(c_str[0]);
	int total = count_if(c_str, c_str + length, lengthThan3);
	return 0;
}

上面可以得到数组中长度大于3的字符串有3个。

但是现在想求字符串大于4个,5个。。。的呢?  当然不嫌麻烦可以写各个对应的function。

现在要说的是另外两个方法:

1,用函数对象

// 定义类 LengthThan
class LengthThan
{
public:
	LengthThan(int length): length_(length) {}
	bool operator()(const char* c)
	{
		return strlen(c) > length_;
	}
private:
	int length_;
};
int a_len = 3;
int total = count_if(c_str, c_str + length, LengthThan(a_len)); 

2, 模版传参

template <int t>
bool lengthThan(const char* c)
{
	return strlen(c) > t;
}
int a_len = 3;
int total = count_if(c_str, c_str + length, lengthThan<a_len>); 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值