C++之仿函数
来源:互联网 发布:java面试宝典下载 编辑:程序博客网 时间:2024/05/24 06:29
http://www.cnblogs.com/runnyu/p/6010101.html
仿函数:函数对象;
仿函数(functors)其实就是重载了operator()的对象
#include <iostream>using namespace std;template<typename T>struct m_plus{ T operator()(const T& x, const T& y) { return x + y; }};int main(int argc, char *argv[]){ // 定义其对象 调用其operator() m_plus<int> op; cout << op(1, 2) << endl; // 产生一个匿名对象 这是仿函数的主流用法 cout << m_plus<int>()(1, 2) << endl; return 0;}
1.仿函数可以有自己的状态,而函数指针则不行(有的使用template或者static变量可以实现)。
我们可以这样子使用仿函数:
#include <iostream>using namespace std;template<typename T, T add>struct m_plus{ m_plus() { _add = add; } T operator()(const T& x) { return x + _add; } // 仿函数可以具有自己的状态 int _add;};int main(int argc, char *argv[]){ m_plus<int, 10> op; cout << op(100) << endl; cout << op(200) << endl; return 0;}
2.仿函数可以与函数适配器搭配使用。
举一个例子,例如我们如果要使用count_if算法来计算容器中大于10的元素的个数。
如果我们使用greater<int>作为判别式(二元),而count_if只接受一个一元判别式,这时候我们就需要搭配函数适配器一起使用了。
而函数指针不能直接搭配函数适配器一起使用,具体在分析bind2nd的时候会讲到。
#include <iostream>#include <vector>#include <functional>#include <algorithm>using namespace std;int main(int argc, char *argv[]){ vector<int> coll{ 1, 3, 5, 7, 9, 11, 13, 15 }; // 接着下面有bind2nd的具体实现 cout << count_if(coll.begin(), coll.end(), bind2nd(greater<int>(), 10)) << endl; return 0;}
阅读全文
0 0
- C++ STL之仿函数
- C++STL:仿函数
- C++STL 仿函数
- C++之仿函数
- C++之仿函数
- STL之仿函数
- Monads之仿函数
- C++之仿函数
- STL之仿函数
- STL之仿函数
- STL之仿函数
- C++之仿函数
- STL学习之路之仿函数
- C函数仿写 JAVA::String操作
- 数据结构与C++stl(2) 仿函数
- STL之仿函数,适配器简介
- 模板之泛化仿函数(一)
- 模板之泛化仿函数(二)
- JS原型模式之修改与重写
- Java练手:利用循环绘制等腰三角形
- FLYPRO:矫健灵活的运动型无人机也许是航拍之后的另一片天下 | CES 2016
- [noip2007]树网的核
- Leetcode——第69题
- C++之仿函数
- Mac 版本IDEA "Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachie
- java面试题 10/29总结
- HDU 1102 Constructing Roads【最小生成树】
- 敏捷开发管理在我司的实践
- 康娜的作业
- Android安全–Dex文件格式详解
- CNN实现MNIST手写数字识别
- springAOP背后的原理