函数对象
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课件
相关文章推荐
- ideviceinstaller报Segmentation fault: 11错误解决过程
- 在没有工具的情况下检查SSD 的TRIM功能有没有打开
- 在没有工具的情况下检查SSD 的TRIM功能有没有打开
- jquery源码之when
- 巧用powerpoint制作符合期刊要求的复合图
- XSS的原理分析与解剖
- LocalBroadcastManager原理和机制
- mysql读写分离(主从复制)实现
- How Much Did It Rain? Winner's Interview: 1st place, Devin Anzelmo
- C++程序设计之四书五经[转自2004程序员杂志]--下篇
- SHINE OPENCART 自适应 多用途主题模板 ABC-0021
- SHINE OPENCART 自适应 多用途主题模板 ABC-0021
- 判断主机是否支持远程开机?
- 需求文档的类别及适用情况
- POJ-3279(Fliptile)--简单搜索
- 移动端遇到的问题
- Eclipse快捷键大全
- UVa - 103 - Stacking Boxes
- 什么是硬件以及什么是软件
- UVa - 103 - Stacking Boxes