日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++笔记-仿函数(functor)

發布時間:2025/3/15 c/c++ 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。