STL函式物件當引數和返回值
阿新 • • 發佈:2019-02-03
#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演算法入門的重要點 }