用到了stl中预定义好的函数对象,和函数适配器。
#include <iostream>
#include <functional>
#include <string>
#include<vector>
#include<algorithm>
using namespace std;
struct User
{
User(int age, string name)
{
this->age = age;
this->name = name;
}
int age;
string name;
};
int main()
{
vector<double> ivec{1,2,3,4,4,4,7,8,9,10};
vector<User> vecUsers{ {22,"Jackson"},{42,"Lucy"},{66,"Tom"} };
cout << "4 出现了\t" << count(ivec.begin(), ivec.end(), 4) << "次" << endl;
cout << "偶数个数\t" << count_if(ivec.begin(), ivec.end(), not1(bind2nd(modulus<int>(), 2))) << endl;;
cout << "大于4的个数\t" << count_if(ivec.begin(), ivec.end(),bind2nd(greater<double>(),4)) << endl;;
cout << "年龄小于40的用户个数\t" << count_if(vecUsers.begin(), vecUsers.end(), [](const User& i){return i.age < 40;}) << endl;;
}
底层算法逻辑
#include <iostream>
#include <functional>
#include <string>
#include<vector>
#include<algorithm>
using namespace std;
int count(vector<double>::iterator first,vector<double>::iterator last,double val)
{
int n =0;
for (; first != last; ++first)
{
if (fabs(*first - val) < 0.01)
{
n++;
}
}
return n;
}
int count_if(vector<double>::iterator first, vector<double>::iterator last, function<bool(double)> pred)
{
int n = 0;
for (;first != last ; ++first)
{
if (pred(*first))
{
n++;
}
}
return n;
}
int main()
{
vector<double> ivec{1,2,3,4,4,4,7,8,9,10};
cout << count(ivec.begin(),ivec.end(),4) << endl;
cout << count_if(ivec.begin(), ivec.end(), [](double item)->bool {return item > 4; }) << endl;
}
标签:count,iterator,int,age,个数,指定,vector,include,first
From: https://blog.csdn.net/WNX10086/article/details/140573634