sort()基本使用

头文件:

include

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int main()
  4. {
  5. vector<int> arr = {4,8,9,3,2,4};
  6. sort(arr.begin(),arr.end()); //默认从小到大排序
  7. sort(arr.begin(),arr.end(), greater<int>()); //从大到小排序
  8. for (int a : arr) {
  9. cout<<a<<" ";
  10. }
  11. return 0;
  12. }

sort()自定义排序

法一:

定义:

struct 结构名 { bool operator() (const T & a, const T & b) const { return ……; } };

使用:

sort(数组名 + n1 , 数组名 + n2 , 排序规则结构名());

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. struct cmp {
  4. bool operator() (const int & a, const int & b) const {
  5. return a > b;
  6. }
  7. };
  8. int main()
  9. {
  10. vector<int> arr = {4,8,9,3,2,4};
  11. sort(arr.begin(), arr.end(), cmp());
  12. for (int a : arr) {
  13. cout<<a<<" ";
  14. }
  15. return 0;
  16. }

法二:

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. class cmp{
  4. public:
  5. bool operator() (const int & a, const int & b) const {
  6. return a > b;
  7. }
  8. };
  9. int main()
  10. {
  11. vector<int> arr = {4,8,9,3,2,4};
  12. sort(arr.begin(), arr.end(), cmp());
  13. for (int a : arr) {
  14. cout<<a<<" ";
  15. }
  16. return 0;
  17. }

法三:

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. bool cmp (const int & a, const int & b) {
  4. return a > b;
  5. }
  6. int main()
  7. {
  8. vector<int> arr = {4,8,9,3,2,4};
  9. sort(arr.begin(), arr.end(), cmp);
  10. for (int a : arr) {
  11. cout<<a<<" ";
  12. }
  13. return 0;
  14. }

法四:

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int main()
  4. {
  5. vector<int> arr = {4,8,9,3,2,4};
  6. sort(arr.begin(), arr.end(), [=] (const int & a, const int & b){
  7. return a > b;
  8. });
  9. for (int a : arr) {
  10. cout<<a<<" ";
  11. }
  12. return 0;
  13. }

结果:

法一至法四的运算结果均为:

9 8 4 4 3 2