C++笔记-仿函数(functor)
生活随笔
收集整理的這篇文章主要介紹了
C++笔记-仿函数(functor)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
STL6個組建:
1. 仿函數;
2. 算法;
3. 迭代器;
4. 空間配置器;
5. 容器;
6. 適配器;
?
仿函數一般不會單獨使用,主要是為了搭配STL算法。
函數指針不能滿足STL對抽象性的要求,不能滿足軟件積木的要求,無法和STL其他組建搭配;
本質就是類重載了一個operator(),創建一個行為類似函數的對象。
如下C++容器排序的過程。
程序運行截圖都這樣:
C++排序過程
#include <iostream> #include <algorithm>using namespace std;bool mySort(int a, int b) {return a > b; }void display(int a) {cout << a << " "; }int main() {int arr1[] = { 5, 4, 2, 1, 7, 99 };sort(arr1, arr1 + 6, mySort);for_each(arr1, arr1 + 6, display);getchar();return 0; }C++模板
#include <iostream> #include <algorithm>using namespace std;template<class T> inline bool mySort(T const &a, T const &b) {return a > b; }template<class T> inline void display(T const &a) {cout << a << " "; }int main() {int arr1[] = { 5, 4, 2, 1, 7, 99 };sort(arr1, arr1 + 6, mySort<int>);for_each(arr1, arr1 + 6, display<int>);getchar();return 0; }使用C++仿函數來做:
#include <iostream> #include <algorithm>using namespace std;struct Sort {bool operator()(int a, int b) {return a < b;} };struct Display {void operator()(int a) {cout << a << " ";} };int main() {int arr1[] = { 5, 4, 2, 1, 7, 99 };sort(arr1, arr1 + 6, Sort());for_each(arr1, arr1 + 6, Display());getchar();return 0; }使用C++仿函數模版來做:
#include <iostream> #include <algorithm>using namespace std;template<class T> struct Sort {bool operator()(T const &a, T const &b) {return a < b;} };template<class T> struct Display {void operator()(T const &a) {cout << a << " ";} };int main() {int arr1[] = { 5, 4, 2, 1, 7, 99 };sort(arr1, arr1 + 6, Sort<int>());for_each(arr1, arr1 + 6, Display<int>());getchar();return 0; }?
?
?
總結
以上是生活随笔為你收集整理的C++笔记-仿函数(functor)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt文档阅读笔记-DTLS server
- 下一篇: s3c2440移植MQTT