C++ STL(4):计算元素个数

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

//计算元素个数
int main()
{
	/************************************************************************/
	//count
	/************************************************************************/
	//计算范围[first,last)内与value相等的个数
	/*
		template<class InputIterator, class T> inline
		size_t count(
			InputIterator First,
			InputIterator Last,
			const T& Value
		);
	*/

	int a[] = {2, 0, 4, 6, 0 ,3, 1, -7};
	const int N = sizeof a / sizeof a[0];
	std::cout << "Numbers of equal to zeros is: " 
		<< std::count(a, a + N, 0) << std::endl;    //Numbers of equal to zeros is: 2

	/************************************************************************/
	//count_if
	/************************************************************************/
	//count_if在范围[first,last)内满足条件的元素个数
	/*
		template<class InputIterator, class Predicate>
		typename iterator_traits<InputIterator>::difference_type count_if(
			InputIterator _First, 
			InputIterator _Last,
			Predicate _Pred
		);
	*/
	std::cout << "Numbers of equal to zeros is: " << 
	std::count_if(a, a + N, std::bind1st(std::equal_to<int>(),0)) 
		<< std::endl;    //Numbers of equal to zeros is: 2

	std::cout << "Numbers of greater equal 0 is: " << 
	std::count_if(a, a + N, std::bind1st(std::less_equal<int>(),0)) 
		<< std::endl;    //Numbers of greater equal 0 is: 7

	return 0;
}
测试结果:

图片


====================打个广告,欢迎关注====================

QQ:412425870
csdn博客:
http://blog.youkuaiyun.com/caychen
码云:
https://gitee.com/caychen/
github:
https://github.com/caychen

点击群号或者扫描二维码即可加入QQ群:

328243383(1群)



点击群号或者扫描二维码即可加入QQ群:

180479701(2群)



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值