【快速入門 C++ STL】 demo 演示九:二元謂詞,二元函式物件,函式介面卡
阿新 • • 發佈:2019-02-17
#include<vector> #include<iostream> #include<algorithm> #include<functional> using namespace std; template <typename T> class sum//二元函式物件 { public: T operator()(T &t1, T &t2)// { return t1 + t2; } }; void printFun(vector<int> &obj) { for (vector<int>::iterator it = obj.begin(); it != obj.end(); it++) { cout << *it << " "; } cout << endl; } void pt(int &a) { cout << a << " "; } template <typename T> bool Mycmp(T &t1, T &t2) { if (t1 > t2) return true; else return false; } int main() { vector<int> v1, v2, v3; for (size_t i = 0; i < 3; i++) { v1.push_back(2 * i + 1); v2.push_back(2 * i); } printFun(v1); printFun(v2); //transform 函式物件引數一般不是引用,必須有返回值 //for_each 函式物件引數一般 是引用, 沒有返回值 //使用二元函式物件 v3.resize(3); transform(v1.begin(), v1.end(), v2.begin(), v3.begin(), sum<int>()); for_each(v3.begin(), v3.end(), pt); cout << endl; //使用二元謂詞 sort(v3.begin(), v3.end(), Mycmp<int>); for_each(v3.begin(), v3.end(), pt); cout << endl; //使用函式介面卡 bind2nd 繫結第二個引數 v3.push_back(1); int num = count_if(v3.begin(), v3.end(), bind2nd(equal_to<int>(), 1)); cout << num << endl; system("pause"); return 0; }