您的位置:首页 > 其它

函数对象

2015-07-02 20:09 246 查看

函数对象

一个行为类似函数的对象

可以没有参数,也可以带有若干参数

其功能是获取一个值,或者改变操作的状态。



普通函数就是函数对象

重载了“()”运算符的类的实例是函数对象



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课件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: