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