天天看點

【學習筆記】C++進階程式設計:STL:函數對象

函數對象

函數對象:若一個類重載了運算符“()”,則該類的對象就成為函數對象

Class CMyAverage{ //函數對象類
Public:
Double operator()(inta1,int a2,int a3){ //重載圓括号運算符
         Reurn (double)(a1+a2+a3)/3;
}
};
CMyAverage average;//函數對象
Cout<<average(3,2,3);
           

函數對象的應用執行個體

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <functional>
using namespace std;

int SumSquares(int total ,int value){
	return total+ value*value;
}; 

template<class T>
void PrintInterval(T first, T last){
	//依次輸出 
	for(;first!=last;++first)
		cout<<*first<<" ";
	cout<<endl;
}; 

template<class T>
class SumPowers{
	private:
		int power;
	public:
		SumPowers(int p):power(p){}
		const T operator() (const T &total,const T &value){
			//計算value的power次方,加到total上 
			T v=value;
			for(int i=0;i<power-1;++i)
				v=v*value;
		    return total+v;
		}
};

int main(){
	const int SIZE =10;
	int a1[]={1,2,3,4,5,6,7,8,9,10};
	vector<int> v(a1,a1+SIZE);
	cout<<"1)";PrintInterval(v.begin(),v.end());
	int result=accumulate(v.begin(),v.end(),0,SumSquares);
	cout<<"2)平方和:"<<result<<endl;
	result=
		accumulate(v.begin(),v.end(),0,SumPowers<int>(3));
	cout<<"3)立方和:"<<result<<endl;
	result=
		accumulate(v.begin(),v.end(),0,SumPowers<int>(4));
	cout<<"4)4次方和:"<<result; 
	return 0;
}


//解釋用:
int accumulate(vector<int>::iterator first,vector<int>::iterator last, int init, int (*op)(int ,int )) {
	//op是一個函數指針 
	for(;first!=last;first++)
		init=op(init,*first);
		//調用sumsquare(init,*first)-->> init += first*first; 
	return init;
}


           

輸出結果:

1)1 2 3 4 5 6 7 8 9 10

2)平方和:385

3)立方和:3025

4)4次方和:25333

STL函數對象類模闆(實作了圓括号成員函數,通過他們可以生成函數對象)

Equal_to

Greater

Less

……

頭檔案:<functional>

關聯容器和STL中許多算法,都是可以用函數或函數對象自定義比較器的。在自定義了比較器op的情況下,以下三種說法是等價的:

1)  x小于y

2)  op(x,y)傳回值為true

3)  y大于x

例子

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

template <class T,class Pred>
T  MyMax(T first , T last, Pred myless){
	T tmpMax=first;
	for(;first!=last;++first){
		if(myless(*tmpMax, *first))
			tmpMax=first;
	}
	return tmpMax;
};

class MyLess{
	public:
		bool operator()(int a1,int a2){
		//比較規則:誰的個位數小,誰就小 
			if((a1 %10)<(a2%10))
				return true;
			else
				return false;
		}
}; 

bool MyCompare(int a1,int a2){
	if((a1%10)<(a2 %10))
	//誰的個位數大,誰就小 
		return false;
	else
		return true;
}

int main(){
	int a[]={35,7,13,19,12};
	cout<<*MyMax(a,a+5,MyLess())<<endl;
	cout<<*MyMax(a,a+5,MyCompare)<<endl;
	return 0;
}
           

輸出結果:

19

12