STL內建了一些函數對象。分為:算數類函數對象,關系運算類函數對象,邏輯運算類仿函數。這些仿函數所產生的對象,用法和一般函數完全相同,當然我們還可以產生無名的臨時對象來履行函數功能。使用內建函數對象,需要引入頭文件 functional
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
//內建函數對象頭文件
#include <functional>
#include <vector>
#include <algorithm>void test01()
{//template<class T> T negate<T>//取反仿函數negate<int>n;cout << n(10) << endl;//加法 template<class T> T plus<T>//加法仿函數plus<int> p;cout << p(1, 1) << endl;
}//template<class T> bool greater<T>//大于void test02()
{vector<int>v;v.push_back(10);v.push_back(30);v.push_back(50);v.push_back(20);v.push_back(40);sort(v.begin(), v.end(), greater<int>());for_each(v.begin(), v.end(), [](int val){ cout << val << " "; });
}int main(){//test01();test02();system("pause");return EXIT_SUCCESS;
}
-------分割線--------
sort 排序,第三個參數可以是函數名,也可以是函數對象
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;bool myparse(int v1, int v2) {return v1 > v2;
}
class MyParse {
public:bool operator() (int v1, int v2) {return v1 > v2;}
};
void test1() {vector<int> v1;v1.push_back(20);v1.push_back(35);v1.push_back(5);for (vector<int>::iterator it = v1.begin(); it != v1.end(); ++it) {cout << *it << endl;}sort(v1.begin(), v1.end());cout << "--" << endl;for (vector<int>::iterator it = v1.begin(); it != v1.end(); ++it) {cout << *it << endl;}/*sort(v1.begin(), v1.end(), myparse); // 通過函數,可以實現自定義排序cout << "--" << endl;for (vector<int>::iterator it = v1.begin(); it != v1.end(); ++it) {cout << *it << endl;}*/sort(v1.begin(), v1.end(), MyParse()); // 通過函數對象, 也可以實現自定義排序cout << "--" << endl;for (vector<int>::iterator it = v1.begin(); it != v1.end(); ++it) {cout << *it << endl;}
}
int main()
{test1();return 0;
}