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

歡迎訪問 生活随笔!

生活随笔

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

c/c++

C++STL总结笔记(二)——仿函数(函数对象)

發布時間:2023/12/10 c/c++ 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++STL总结笔记(二)——仿函数(函数对象) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

  • 一、概念
  • 總結


一、概念

仿函數又稱函數對象,即重載了函數調用運算符()的類的對象。
優勢:
1.仿函數對象的內部可以有自己的狀態,可以實現一些其他的功能。
2.函數對象可以作為參數進行傳遞。

當仿函數類內重載的返回值是bool類型被稱為謂詞,形參為1個為1元謂詞,2個是2元謂詞。

class Compare { public:Compare(){n = 0;}//一元謂詞bool operator()(int a){n++;return a > 5; }//二元謂詞bool operator()(int a, int b){n++;return a > b; }int n; };bool Print(Compare& c, int a, int b) {return c(a, b); }int main() {Compare c;//函數對象//調用重載()cout << c(1, 2) << endl;cout << c(3, 2) << endl;cout << c(2, 1) << endl;//可實現計數功能cout << c.n << endl;//作為參數傳遞cout << Print(c, 3, 6) << endl;system("pause"); } 0 1 1 3 0

STL里內置了一些仿函數類型,包括算術仿函數、關系仿函數、邏輯仿函數。

算數仿函數包括+,-,*,/, 取模,取反。

#include<iostream> #include<string> #include<functional>//STL內部函數對象頭文件 using namespace std;int main() {//算術仿函數//加法plus<int>a;cout << a(1, 2) << endl;//減法minus<int>a1;cout << a1(1, 2) << endl;//乘法multiplies<int>a2;cout << a2(1, 2) << endl;//除法divides<int>a3;cout << a3(2, 1) << endl;//取反仿函數negate<int>b;cout << b(1) << endl;//取模仿函數modulus<int>c;cout << c(3,2) << endl;system("pause"); } 3 -1 2 2 -1 1

關系仿函數包括>,<,=,<=,>=,!=。

#include<iostream> #include<string> #include<list> #include<functional>//STL內部函數對象頭文件 using namespace std;int main() {list<int>L;//插入L.push_back(1);L.push_back(2);list<int>L1;L1 = L;//內置的關系仿函數,大于//L.sort(greater<int>());//小于//L.sort(less<int>());//小于等于L.sort(greater_equal<int>());for (list<int>::iterator i = L.begin(); i != L.end(); i++){cout << *i << endl;}system("pause"); }

邏輯運算符包括與或非。

list<bool>L1;L1.push_back(true);L1.push_back(false);for (list<bool>::iterator i = L1.begin(); i != L1.end(); i++){cout << *i << endl;}list<bool>L2;L2.resize(L1.size());transform(L1.begin(), L1.end(), L2.begin(),logical_not<bool>());for (list<bool>::iterator i = L2.begin(); i != L2.end(); i++){cout << *i << endl;}

總結

對于簡單的容器之間的運算可以使用內置的仿函數,如果想自定義更復雜的仿函數,就需要自己構建仿函數類。

總結

以上是生活随笔為你收集整理的C++STL总结笔记(二)——仿函数(函数对象)的全部內容,希望文章能夠幫你解決所遇到的問題。

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