1. 程式人生 > >C++11--function

C++11--function

1:function作用:提供函式統一的介面,是可呼叫函式的包裝器, 函式/函式指標/lambda/偽函式;

2:傳統多型實現

#include <iostream>
#include <functional>
using namespace std;
class opr{
public:
	virtual int op(int x,int y)=0;
};
class Add:public opr{
public:
	int op(int x,int y){
		return x+y;
	}
};
class Miu:public opr{
public:
	int op(int x,int y){
		return x-y;
	}

};
int main() {
	Add add;
	Miu miu;
	cout<<add.op(2,1)<<endl;
	cout<<miu.op(2,1)<<endl;
	return 0;
}

3:function使用例項

#include <iostream>
#include <functional>
#include <map>
using namespace std;
int add(int x,int y){
	return x+y;
}
int miu(int x,int y){
	return x-y;
}
class del{
public:
	int operator()(int x,int y){
		return x/y;
	}
};
typedef int(*mix)(int x,int y);
int main() {
	//函式
	auto op = function<int(int x,int y)>(add);
	cout<<op(4,5)<<endl;
	//函式指標
	mix m = miu;
	op = function<int(int x,int y)>(m);
	cout<<op(4,5)<<endl;
	//lambda
	auto mul=[](int x, int y){return x*y;};
	op = function<int(int ,int )>(mul);
	cout<<op(4,5)<<endl;

	del di;
	op = function<int(int,int)>(di);
	cout<<op(4,5)<<endl;


	//更深層次的包裝
	map<string,function<int(int,int)>> mmp ={
			{"+",add},
			{"-",m},
			{"*",mul},
			{"/",di}
	};
	cout<<mmp["+"](2,3)<<endl;
	cout<<mmp["-"](2,3)<<endl;
	cout<<mmp["*"](2,3)<<endl;
	cout<<mmp["/"](2,3)<<endl;
	return 0;
}

4:進階

void selectSort(int *p,int n,function<int(int,int)> compare){
	for(int i=0;i<n-1;i++)
	{
		for(int j=i+1;j<n-1;j++)
		{
			p[i]^=p[j];
			p[j]^=p[i];
			p[i]^=p[j];
		}
	}
}

	int arr[] = {1,3,5,7,9,2,4,6,8,10};
	selectSort(arr,sizeof(arr)/sizeof(*arr));

	for_each(arr,arr+10,[](int &i){cout<<i<<endl; });
//fuction作為引數實現回撥.
void selectSort(int *p,int n,function<int(int,int)> compare){
	for(int i=0;i<n-1;i++)
	{
		for(int j=i+1;j<n-1;j++)
		{
		if(compare(p[i],p[j]))
		{
			p[i]^=p[j];
			p[j]^=p[i];
			p[i]^=p[j];
			}
		}
	}
}
	int arr[] = {1,3,5,7,9,2,4,6,8,10};
	selectSort(arr,sizeof(arr)/sizeof(*arr),[](int x,int y){return x>y;});
//fuction作為類成員作為回撥
class Fuc1{
public:
	void operator()(){cout<<"class fuc1"<<endl;}
};
class Fuc2{
public:
	void operator()(){cout<<"class fuc2"<<endl;}
};

class Fuc3{
public:
	void operator()(){cout<<"class fuc3"<<endl;}
};
class Fuc4{
public:
	void operator()(){cout<<"class fuc4"<<endl;}
};

	Fuc1 f1;Fuc2 f2;Fuc3 f3;Fuc4 f4;
	objt oji(f1,f2,f3,f4);
	oji.notify();