C++ STL 算法:元素计数

一、通用算法:
#include <algorithm>
#include <functional>//预定义函数对象和函数适配器
一元谓词:返回值为bool类型的函数或函数对象,且参数只有一个,如:
bool isEven(int elem)
{
  return elem % 2 == 0;
}
1、count
num = count(ivec.begin(), ivec.end(), 4);
cout << "有" << num << "个4" << endl;
2、count_if
例1
num = count_if(ivec.begin(), ivec.end(),isEven);//计算有多少个偶数
例2
num = count_if(ivec.begin(), ivec.end(),bind2nd(greater<int>(),6));//将6绑定到第二个参数
cout << "有" << num << "个数大于6" << endl;
例3
//                                                                                          param1 % 2
num = count_if(ivec.begin(), ivec.end(), not1(bind2nd(modulus<int>(),2)));//将2绑定到第二个参数,not1是参数为一个的取反的函数适配器
cout << "有" << num << "个偶数" << endl;

二、关联容器的等效成员函数(速度比通用算法快)
1.set.count
2.multiset.count
3.map.count
4.multimap.count
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值