【学习笔记】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

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值