STL函数对象当参数和返回值
2018-04-06 23:57
375 查看
#include<iostream> #include<string> #include<vector> #include<list> #include<set> #include<algorithm> #include<functional> using namespace std; template<typename T> class ShowElemt { public: ShowElemt() { n = 0; } void operator()(T&t) { n++; // printN(); cout << t <<" "; } void printN() { cout << "n:" << n << " "; } private: int n; }; //模板函数 template<typename T> void FunShowElemt(T &t) { cout << "FunShowElemt:" << t << " "; } //普通函数 void FunShowElemt2(int &t) { cout << "FunShowElemt2:" << t << " "; } void main01() { int a = 10; ShowElemt<int> showElemt; showElemt(a);//函数对象的执行很像一个函数 伪函数 FunShowElemt<int>(a); FunShowElemt2(a); } //函数对象是属于类对象,能突破函数概念,能保持调用状态信息 //for_each算法中 函数对象做函数参数 //for_each算法中 函数对象当返回值 void main02() { vector<int> v1; v1.push_back(1); v1.push_back(3); v1.push_back(5); for_each(v1.begin(), v1.end(), ShowElemt<int>()); cout << endl; for_each(v1.begin(), v1.end(), FunShowElemt2); cout << endl; ShowElemt<int> show1; /* template<class _InIt,class _Fn1> inline _Fn1 for_each(_InIt _First, _InIt _Last, _Fn1 _Func) { // perform function for each element _DEBUG_RANGE(_First, _Last); _DEBUG_POINTER(_Func); _For_each(_Unchecked(_First), _Unchecked(_Last), _Func); return (_STD move(_Func)); } */ //for_each算法的函数 对象的传递 是元素值传递,不是引用传递 for_each(v1.begin(), v1.end(), show1); show1.printN(); cout << endl; show1 = for_each(v1.begin(), v1.end(), show1);//通过for_each算法的返回值看调用的次数 show1.printN(); //结论要点:分清楚 stl算法返回的值是迭代器还是谓词(函数对象)是stl算法入门的重要点 }
相关文章推荐
- STL算法设计理念 - 函数对象和函数对象当参数和返回值
- 如果函数的传入参数和返回值是对象
- C++,当函数参数或者返回值是对象......(★firecat推荐★)
- Python开发基础-Day6-函数参数、嵌套、返回值、对象、命名空间和作用域
- 在JavaScript中使用Qt对象成员函数的参数及返回值问题
- python基础之函数参数、嵌套、返回值、对象、命名空间和作用域
- C++函数参数传值OR传引用_C++函数返回值返回对象OR对象引用
- stl算法设计理念_函数对象和函数对象当参数和返回值
- stl算法设计理念:函数对象和函数对象当参数和返回值
- STL算法设计理念 - 函数对象和函数对象当参数和返回值
- JavaScript-4.3函数的参数和返回值,参数数目不确定的函数调用---ShinePans
- 函数多个返回值(返回多个参数/局部变量)通过双重指针来实现
- perl 函数参数传递与返回值(一)
- python函数参数是值传递还是引用传递:取决于对象内容可变不可变
- Swift 2.0 函数 定义、调用、参数返回值、函数类型、嵌套函数
- c++ stl Function Objects 函数对象
- 函数,参数及参数解构, 返回值,作用域
- arguments对象验证函数的参数是否合法
- php引用(&)变量引用,函数引用,对象引用和参数引用用法详解