C++ STL标准库:算法<algorithm> count() count_if() 计数函数用法

本文介绍了C++中std::count和std::count_if两个函数。std::count用于计算范围内值等于指定值的元素数,使用运算符==比较;std::count_if则返回满足特定条件的元素个数,通过一元函数判断。还说明了两函数的参数和返回值情况。

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

std::count

函数原型:

template <class InputIterator, class T>
  typename iterator_traits<InputIterator>::difference_type
    count (InputIterator first, InputIterator last, const T& val);

计算范围内值的表达式

返回[first,last)范围内比较等于val的元素数。

函数使用运算符==将各个元素与val进行比较。

参数:
first, last:
在元素序列的初始和最终位置输入迭代器。使用的范围是[first,last],它包含first和last之间的所有元素,包括first指向的元素,但不包括last指向的元素。

val:
要匹配的值。
T应为支持与InputIterator使用运算符==(元素为左侧操作数,val为右侧操作数)的元素进行比较的类型。

返回值:
范围[first,last]中比较等于val的元素数。
返回类型(iterator_traits::difference_type)是有符号整数类型。


std::count_if

函数原型:

template <class InputIterator, class UnaryPredicate>
  typename iterator_traits<InputIterator>::difference_type
    count_if (InputIterator first, InputIterator last, UnaryPredicate pred);

返回满足条件范围内的元素个数

返回pred为true的范围内[first,last]的元素个数。

参数:
first,last:
在元素序列的初始和最终位置输入迭代器。使用的范围是[first,last],它包含first和last之间的所有元素,包括first指向的元素,但不包括last指向的元素。

pred:
一元函数,接受范围内的元素作为参数,并返回一个可转换为 bool 的值。返回的值指示此函数是否对元素进行计数。

函数不应修改其参数。

这既可以是函数指针对象,也可以是函数对象。

返回值:
[first,last]应用于pred中不返回false的元素数

返回类型(iterator_traits::difference_type)是有符号整数类型。


#include <functional>
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

template <class T>
void FillValue(T& vect, int first, int last)
{
	if (last >= first)
	{
		for (int i = first; i <= last; ++i)
			vect.insert(vect.end(), i);
	}
	else
	{
		cout << " The indexes is error: last < first. " << endl;
	}
}

void print(int elem)
{
	cout << elem << " ";
}

bool isEven(int elem)
{
	return elem % 2 == 0;
}

void main()
{
	// 初始化myvector
	vector <int> myvector;
	FillValue(myvector, 1, 9);
	for_each(myvector.begin(), myvector.end(), print);
	cout << endl;
	
	// 计算4的个数
	int ct = count(myvector.begin(), myvector.end(), 4);
	// 计算偶数个数
	int ctif = count_if(myvector.begin(), myvector.end(), isEven);
	// 计算大于2的个数
	int ctg = count_if(myvector.begin(), myvector.end(), bind2nd(greater<int>(), 2));
	cout << "等于4的元素个数:" << ct << endl;
	cout << "偶数元素个数:" << ctif << endl;
	cout << "超过2的元素个数: " << ctg << endl;
	cout << endl;
}

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

超级D洋葱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值