本博文主要讲解了count count_if 的使用
- 实例
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int a[] = {1,2,3,4,5,6,6,7,8,9};
int len = sizeof(a)/sizeof(int);
cout<<"请输入你想查询的数:"<<endl;
int wantNum;
cin>>wantNum;
int nCount = count(a,a+len,wantNum);
cout<<wantNum<<"出现的次数为:"<<nCount<<endl;
system("pause");
return 0;
}
2.实例2
/*
*【1】查询有多少学生成绩为80
*【2】查询有多少学生成绩大于80
*【3】查询有多少学生成绩小于80
*/
#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
using namespace std;
class student
{
public:
int stdno;
string strName;
int grade;
student(int stdno,string strName,int grade)
{
this->stdno = stdno;
this->strName = strName;
this->grade = grade;
}
bool operator==(int grade)
{
return this->grade == grade;
}
};
//
class macthExpress
{
int grade;
public:
macthExpress(int grade)
{
this->grade = grade;
}
bool operator() (student s)
{
return s.grade > grade;
}
};
class macthExpressLow
{
int grade;
public:
macthExpressLow(int grade)
{
this->grade = grade;
}
bool operator() (student s)
{
return s.grade < grade;
}
};
int main()
{
vector<student>stdVec;
student s1(1,"lijia",100);
student s2(2,"renyin",60);
student s3(3,"zhangchen",90);
student s4(4,"xiaodeguang",80);
student s5(5,"weiyimeng",80);
stdVec.push_back(s1);
stdVec.push_back(s2);
stdVec.push_back(s3);
stdVec.push_back(s4);
stdVec.push_back(s5);
///等于80分的个数
int nCount = count(stdVec.begin(),stdVec.end(),80);
cout<<"分数等于80分的有"<<nCount<<"个"<<endl;
//大于80分的个数
nCount = count_if(stdVec.begin(),stdVec.end(),macthExpress(80));
cout<<"大于80分的个数:"<<nCount<<endl;
//小于80分的个数
nCount = count_if(stdVec.begin(),stdVec.end(),macthExpressLow(80));
cout<<"小于80分的个数:"<<nCount<<endl;
system("pause");
return 0;
}