#include "stdafx.h"
#include <vector>
#include <algorithm>
#include <string>
#include <functional>
using namespace std;
class student
{
public:
int NO;
string strName;
int score;
public:
//构造函数
student(int NO,string strName,int score)
{
this->NO=NO;
this->strName=strName;
this->score=score;
}
//运算符重载 ==
bool operator==(int NO)
{
return (this->NO==NO);
}
};
class MatchExpress
{
private:
int lowGrade;
int highGrade;
public:
MatchExpress(int lowScore,int highScore)
{
lowGrade=lowScore;
highGrade=highScore;
}
bool operator()(student &s)
{
return (s.score>=lowGrade && s.score<=highGrade);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
vector<student> v;
student s1(101,"ss1",60);
student s2(102,"ss2",70);
student s3(103,"ss3",80);
student s4(104,"ss4",90);
v.push_back(s1);
v.push_back(s2);
v.push_back(s3);
v.push_back(s4);
//----------------------------------------------
//对象查找,必须重载运算符"=="
vector<student>::iterator ite;
ite=find(v.begin(),v.end(),102);//运算符(==)重载即可
if(ite!=v.end())
printf("102 is found in %d\n",ite-v.begin());
else
printf("102 is not found\n");
//----------------------------------------------
//函数对象类MatchExpress的使用,可进行带参数的范围查询
int k=count_if(v.begin(),v.end(),MatchExpress(75,80));
printf("above [75,80] is found in %d\n",k);
getchar();
return 0;
}
1)定义了一个函数对象类MatchExpress,重载了operator() (student & s)运算符函数。
2)当执行count_if语句时,把第三个参数MatchExpress(75,80)作为函数对象,先调用构造函数给MatchExpress的成员变量赋值(lowGrade,hIghGrade),
然后向量中的每个学生对象作为函数对象的参数调用operator() (student& s)函数,判断学生的成绩是否在范围之内。
当然,可在MatchExpress类中定义更多的成员变量,形成更复杂的表达式。