count_if (InputIterator first, InputIterator last, UnaryPredicate pred);
该函数可以计算得到,容器内,在[first,last)区间上,满足pred函数条件的元素的个数。
first、last表示到元素序列起始和最终位置的输入迭代器。
pred函数体内返回的是bool类型,表示该元素是否被计数。关于pred,可以先定义,后引用,也可以采用lambda表达式风格,直接写在参数列表当中。一共有四种使用方法,如下:
#include <iostream> // std::cout
#include <algorithm> // std::count_if
#include <vector> // std::vector
#include <functional> // std::bind
//function
bool fun(int i)
{
return i%2==1;
}
//仿函数
class funn
{
public:
bool operator()(int i){
return i%2==1;
}
};
//bind
class funny
{
public:
bool operator()(int i,int j){
return i%j==1;
}
};
int main () {
std::vector<int> myvector;
for (int i=1; i<10; i++) myvector.push_back(i); // myvector: 1 2 3 4 5 6 7 8 9
//lambda
//int mycount = count_if (myvector.begin(), myvector.end(), [](int i){return (i%2==1);});
//function
//int mycount = count_if (myvector.begin(), myvector.end(), fun);
//仿函数
//int mycount = count_if (myvector.begin(), myvector.end(), funn());
//bind
auto f=std::bind(funny(),std::placeholders::_1,2);
int mycount = count_if (myvector.begin(), myvector.end(), f);
std::cout << "myvector contains " << mycount << " odd values.\n";
//myvector contains 5 odd values.
return 0;
}
其中,bind方法中使用到的std::placeholders::_1 是一个占位符,代表这个位置将在函数调用时,被传入的第一个参数所替代。