sort()基本使用
头文件:
include
#include<bits/stdc++.h>using namespace std;int main(){vector<int> arr = {4,8,9,3,2,4};sort(arr.begin(),arr.end()); //默认从小到大排序sort(arr.begin(),arr.end(), greater<int>()); //从大到小排序for (int a : arr) {cout<<a<<" ";}return 0;}
sort()自定义排序
法一:
定义:
struct 结构名 { bool operator() (const T & a, const T & b) const { return ……; } };
使用:
sort(数组名 + n1 , 数组名 + n2 , 排序规则结构名());
#include<bits/stdc++.h>using namespace std;struct cmp {bool operator() (const int & a, const int & b) const {return a > b;}};int main(){vector<int> arr = {4,8,9,3,2,4};sort(arr.begin(), arr.end(), cmp());for (int a : arr) {cout<<a<<" ";}return 0;}
法二:
#include<bits/stdc++.h>using namespace std;class cmp{public:bool operator() (const int & a, const int & b) const {return a > b;}};int main(){vector<int> arr = {4,8,9,3,2,4};sort(arr.begin(), arr.end(), cmp());for (int a : arr) {cout<<a<<" ";}return 0;}
法三:
#include<bits/stdc++.h>using namespace std;bool cmp (const int & a, const int & b) {return a > b;}int main(){vector<int> arr = {4,8,9,3,2,4};sort(arr.begin(), arr.end(), cmp);for (int a : arr) {cout<<a<<" ";}return 0;}
法四:
#include<bits/stdc++.h>using namespace std;int main(){vector<int> arr = {4,8,9,3,2,4};sort(arr.begin(), arr.end(), [=] (const int & a, const int & b){return a > b;});for (int a : arr) {cout<<a<<" ";}return 0;}
结果:
法一至法四的运算结果均为:
9 8 4 4 3 2
