STL中的二元函数binary_function

82 篇文章 0 订阅

      

       函数对象是重载了operator()的类的一个实例,operator()是函数调用运算符。

标准C++库根据operator()参数个数加以划分,主要有以下几种类型:

       1  发生器:一种没有参数且返回一个任意类型值的函数对象,例如随机数发生器。

       2  一元函数:一种只有一个任意类型的参数,且返回一个可能不同类型值的函数对象。

       3  二元函数:一种有两个任意类型的参数,且返回一个可能不同类型值的函数对象。

       4  一元判定函数:返回bool型值的一元函数。

       5  二元判定函数:返回bool型值的二元函数。


     样例

     //1   一个自定义类型

     

#include <string>
#include <iostream>
using namespace std;

class Student
{
public:
	Student(void);
	~Student(void);

public:
	string _stuName;
	float  _stuScore;

public:
	Student(string stuName,float stuScore)
	{
		_stuName=stuName;
		_stuScore=stuScore;
	}

	//布尔运算符重载
	bool operator <(const Student& stu)
	{
		return _stuScore<stu._stuScore;
	}

	//()运算符重载
	void operator()(const Student& stu)
	{
		cout<<stu._stuName<<"  "<<stu._stuScore<<endl;
	}


};
 

//2  重载系统二元函数

#pragma once
#include <functional>
using namespace std;


//不能有构造函数
template <class inPara , class outPara>
class binary_sort:public binary_function<inPara,outPara,bool>
{
public:
	bool operator()(inPara in1,outPara in2)
	{
		return in1<in2;
	}
};

//3  使用样例

 

#include "stdafx.h"

#include <string>
#include <vector>
#include <iostream>
#include <functional>
#include <algorithm>

#include "Student.h"
#include "binary_sort.h"


int _tmain(int argc, _TCHAR* argv[])
{

	vector<Student>v;

	//向量赋值
	Student s1("11111",67);
	v.push_back(s1);

	Student s2("2222",45);
	v.push_back(s2);

	Student s3("33333",78);
	v.push_back(s3);

   //利用函数对象,输出各个元素
   cout<<"before sort()"<<endl;
   for_each(v.begin(),v.end(),Student());


   cout<<"after sort()"<<endl;
   //利用二元判定函数进行排序
   sort(v.begin(),v.end(),binary_sort<Student&,Student&>());

   for_each(v.begin(),v.end(),Student());


	getchar();
	return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值