原创


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

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!