函数对象

函数对象

  • 一个行为类似函数的对象
  • 可以没有参数,也可以带有若干参数
  • 其功能是获取一个值,或者改变操作的状态。
    • 普通函数就是函数对象
    • 重载了“()”运算符的类的实例是函数对象

1.普通函数对象
#include <iostream>   
#include <numeric> //包含数值算法头文件
using namespace std;

//定义一个普通函数
int mult(int x, int y) { return x * y; };

int main() {
	int a[] = { 1, 2, 3, 4, 5 };
	const int N = sizeof(a) / sizeof(int);
	cout << "The result by multipling all elements in a is "
		<< accumulate(a, a + N, 1, mult)
		<< endl;
	return 0;
}

运行结果:

2.定义内对象:
#include <iostream>   
#include <numeric> //包含数值算法头文件
using namespace std;

class MultClass{  //定义MultClass类
public:
	//重载操作符operator()
	int operator() (int x, int y) const { return x * y; }
};

int main() {
	int a[] = { 1, 2, 3, 4, 5 };
	const int N = sizeof(a) / sizeof(int);
	cout << "The result by multipling all elements in a is "
		<< accumulate(a, a + N, 1, MultClass())//将类multclass传递给通用算法
		<< endl;
	return 0;
}

运行结果:
3. 利用STL标准函数对象
#include <iostream>   
#include <numeric> //包含数值算法头文件
#include <functional>  //包含标准函数对象头文件
using namespace std;

int main() {
	int a[] = { 1, 2, 3, 4, 5 };
	const int N = sizeof(a) / sizeof(int);
	cout << "The result by multipling all elements in a is "
		<< accumulate(a, a + N, 1, multiplies<int>())
		<< endl;//将标准函数对象传递给通用算法
	return 0;
}

运行结果:
4. 利用STL中的二元谓词函数对象
#include <functional>
#include<iostream>
#include<iterator>
#include<vector>
#include<algorithm>
using namespace std;

int main() {
	int intArr[] = { 30, 90, 10, 40, 70, 50, 20, 80 };
	const int N = sizeof(intArr) / sizeof(int);
	vector<int> a(intArr, intArr + N);
	cout << "before sorting:" << endl;
	copy(a.begin(), a.end(), ostream_iterator<int>(cout, "\t"));
	cout << endl;

	sort(a.begin(), a.end(), greater<int>());

	cout << "after sorting:" << endl;
	copy(a.begin(), a.end(), ostream_iterator<int>(cout, "\t"));
	cout << endl;
	return 0;
}

运行结果:

来自清华大学MOOC课件
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值