备注:sort内部使用的快排

C++定义:

  1. void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);

参数解释:

  1. 第一个参数first:是要排序的起始地址 [ 包含 ]
  2. 第二个参数last:是结束的地址 [ 不包含 ]
    • 最后一个数据的后面一个的地址
  3. 第三个参数comp是排序准则:可以是从升序也可是降序

    • 如果第三个参数不写,则默认的排序方法是从小到大排序

      1.常规默认排序


      作用
      将数字从小到大排序

      使用
  4. vector 中

    1. vector<int>V;
    2. V.push_back(-1);
    3. V.push_back(12);
    4. V.push_back(8);
    5. sort (num.begin(),num.end());//从小到大排序
  5. 数组中

    1. int a[]={45,12,34,77,90,11,2,4,5,55};
    2. sort(a,a+10);
  6. 元素自身包含了比较关系,如int,double等基础类型

    • 可以直接进行比较greater()** **递减less() **递增**
      1. int s[]={34,56,11,23,45};
      2. vector<int>arr(s,s+5);//拷贝数组s的数据
      3. sort(arr.begin(),arr.end(),greater<int>());//递减
      4. sort(arr.begin(),arr.end(),less<int>()); //递增

      2.自定义cmp准则 [ 5种方式 ]


      作用**
      按照自己想要的方式来排序

      1.在vector中按照自定义准则排序

      1. # include<iostream>
      2. # include<algorithm>
      3. # include<vector>
      4. using namespace std;
      5. bool cmp(int a,int b){
      6.   return a>b;
      7. }
      8. int main(void){
      9.   int a[]={45,12,34,77,90,11,2,4,5,55};
      10.   sort(a,a+10,cmp);//自定义排序准则
      11. system("pause");
      12. return 0;
      13. }

      2. 元素本身为class或者struct

      写在类内 ( 依靠重载 )

      两种方式:
  7. sort(vec.begin(), vec.end());

    • 备注:类内重载 <
  8. sort(vec.begin(), vec.end(),Node());

    • 备注:类内重写仿函数( **重载()**)

      1. struct Node{
      2. int x, y;
      3. Node(int x,int y):x(x),y(y){}
      4. // 1.重载"<"运算符(写在类内部)
      5. bool operator<(const Node& a)const { // 返回true,表示this的优先级小于a
      6. // x大的排在前面;x相同时,y大的排在前面
      7. if (x_ == a.x_) return y_ > a.y_;
      8. return x_ > a.x_;
      9. }
      10. // 2.重写仿函数(写在类内部)
      11. bool operator()(Node& a, Node& b) const { // 返回true,表示this的优先级小于a
      12. // x大的排在前面;x相同时,y大的排在前面
      13. if (a.get_x() == b.get_x()) return a.get_y() > b.get_y();
      14. return a.get_x() > b.get_x();
      15. }
      16. };

      写在类外

      两种方式:

  9. sort(vec.begin(), vec.end());

    • 备注:类外重载 <
      1. bool operator<(Node& a, Node& b) { // 返回true,表示this的优先级小于a
      2. // x大的排在前面;x相同时,y大的排在前面
      3. if (a.get_x() == b.get_x()) return a.get_y() > b.get_y();
      4. return a.get_x() > b.get_x();
      5. }
  10. sort(vec.begin(), vec.end(), cmp) ;

    • 备注:类外重写仿函数类( **重载()**)

注意**
cmp返回值bool类型**

  1. //仿函数类
  2. struct cmp{
  3. bool operator()(node a, node b){
  4. if (a.x == b.x) return a.y >= b.y;
  5. else return a.x > b.x;
  6. }
  7. };