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

歡迎訪問 生活随笔!

生活随笔

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

c/c++

C++ 内建函数对象

發布時間:2023/11/30 c/c++ 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++ 内建函数对象 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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; }

總結

以上是生活随笔為你收集整理的C++ 内建函数对象的全部內容,希望文章能夠幫你解決所遇到的問題。

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