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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM