zoukankan      html  css  js  c++  java
  • Sort函数(C++)

    原创


    C++中内置了sor函数供排序,函数原型为:

    #include<algorithm>  //所属头文件
    sort(begin,end,cmp);    //其中cmp参数可以省略,省略后默认升序排序

    如果要进行降序排序,需要另外定义cmp函数:

    bool cmp(int a,int b){    //降序排序
        return a>b;
    }

    另外还可以对string和结构体进行排序:

    #include<iostream>
    #include<algorithm>
    #include<time.h>
    using namespace std;
    
    bool cmp(int a,int b){
        return a>b;
    }
    
    struct stru{
        int x;
        int y;
    };
    
    bool cmpp(stru a,stru b){
        if(a.x==b.x){    //x坐标同,y坐标降序排序 
            return a.y>b.y;
        }
        return a.x<b.x;    //否则按x坐标升序排序 
    }
    
    int main(){
        //int
        int array[10];
        for(int i=0;i<10;i++){
            array[i]=i;
        }
        sort(array,array+10,cmp);
        for(int i=0;i<10;i++){
            cout<<array[i]<<" ";
        }
        cout<<endl;
        //string
        string str="hello,world";
        sort(str.begin(),str.end());
        cout<<str<<endl;
        //结构体
        srand(time(0));
        struct stru node[10];
        for(int i=0;i<10;i++){
            node[i].x=rand()%20;
            node[i].y=rand()%20;
        }
        sort(node,node+10,cmpp);
        for(int i=0;i<10;i++){
            cout<<node[i].x<<" "<<node[i].y<<endl;
        }
        return 0;
    }

    22:37:40

    2018-09-12

  • 相关阅读:
    SQL server 笔记8
    SQL server 笔记7
    SQL server 笔记6
    SQL server的一些函数即笔记5
    SQL server 练习查询45题(18-45)及笔记4
    SQL server 练习查询45题(1-17)及笔记 3
    SQL server 学习笔记2
    SQL server 学习笔记
    C#复习笔记
    学习递归笔记
  • 原文地址:https://www.cnblogs.com/chiweiming/p/9637867.html
Copyright © 2011-2022 走看看