STL仿函数

一.概念

#include<iostream>
using namespace std;

class Test{
int n,m;
public:
	Test(int n,int m):n(n),m(m){}
	int operator()(){//仿函数对应的类要重载括弧运算符 
		return n+m;
	}
	int operator()(int h){
		return n+m+h;
	}
};

int main(){
	Test t(1,2);
	cout << t.operator()() << endl;
	cout << t() << endl; //简写
	                     //t就是仿函数,模仿函数调用   
	cout << t(3) << endl;//t.operator()(3)
	//匿名对象调用:
	cout << Test(4,5).operator()(6) << endl;
	cout << Test(4,5)(6) << endl; 
} 

例:排序

#include<iostream>
#include<vector>
#include<algorithm>//sort
using namespace std;

bool cmp(int a,int b){
	return a>b;
}
class Cmp{
public:
	bool operator()(int a,int b){
		return a>b;
	}
};
template<class T>
class Compare{
public:
	bool operator()(T a,T b){
		return a>b;
	}
};
template<typename T>
bool compare(T a,T b){
		return a>b;
}

int main(){
	//给vector排序(降序): 
	vector<int> vec = {2,4,6,1,3,5};
	//sort排序(默认为升序,加上Cmp()参数为降序)  
	sort(vec.begin(),vec.end(),cmp);//函数指针 
	sort(vec.begin(),vec.end(),Cmp());//仿函数(默认为升序,加上Cmp()为降序) 
	sort(vec.begin(),vec.end(),Compare<int>());//类模板仿函数 
	sort(vec.begin(),vec.end(),compare<int>);//函数模板 
	sort(vec.begin(),vec.end(),greater<int>());//STL仿函数 
	for(auto n:vec){
		cout << n << " ";
	} 
	cout << endl;
} 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值