函数对象

定义

如果一个类将()运算符重载为成员函数,这个类就称为函数对象类,这个类的对象就是函数对象。函数对象是一个对象,但是使用的形式看起来像函数调用,实际上也执行了函数调用,因而得名。

函数对象应用实例

#include <iostream>
#include <vector>
#include <numeric> //accumulate 在此头文件定义
using namespace std;
template <class T>
void PrintInterval(T first, T last)
{ //输出区间[first,last)中的元素
	for (; first != last; ++first)
		cout << *first << " ";
	cout << endl;
}
int SumSquares(int total, int value)
{
	return total + value * value;
}
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);//v初始化
	cout << "1) "; PrintInterval(v.begin(), v.end());
	int result = accumulate(v.begin(), v.end(), 0, SumSquares);//0 是计算时的初始值
	cout << "2) 平方和:" << result << endl;
	result = accumulate(v.begin(), v.end(), 0, SumPowers<int>(3));//sumPowers<int>(3) 只是相当于sumPowers类的构造 临时变量
	cout << "3) 立方和:" << result << endl;
	result = accumulate(v.begin(), v.end(), 0, SumPowers<int>(4));
	cout << "4) 4次方和:" << result;
	system("pause");
	return 0;
}

sort排序

#include <iostream>
#include <vector>
#include <numeric> //accumulate 在此头文件定义
#include<algorithm>
using namespace std;
class T{
public:
	T(int age, int score) :m_age(age), m_score(score){}
	int m_age;
	int m_score;
	bool operator>(const T&another)const
	{
		return this->m_age > another.m_age;
	}
	void print()
	{
		cout << "age: " << m_age << "score: " << m_score;
		cout << " " << endl;
	}
};
bool compare(const T&t1, const T&t2)
{
	return t1.m_age > t2.m_age;
}
bool compare1(const T&t1, const T&t2)
{
	return t1.operator>(t2);
}
struct Greater{
	bool operator()(const T&t1,const T &t2)
	{
		return t1.m_age > t2.m_age;
	}
};
int main()
{
	vector <T> v;
	for (int i = 0; i < 5; ++i)
	{
		v.push_back(T(i + 10, i));
	}
	for (vector<T>::iterator it = v.begin(); it != v.end(); ++it)
	{
		(*it).print();
	}
	cout << "____________" << endl;
	//sort(v.begin(), v.end(),compare1);
	sort(v.begin(), v.end(), Greater());
	for (vector<T>::iterator it = v.begin(); it != v.end(); ++it)
	{
		(*it).print();
	}
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值