参数化的函数对象

81 篇文章 0 订阅



#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类中定义更多的成员变量,形成更复杂的表达式。

  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值