设为首页 加入收藏

TOP

Sort函数(C++)
2018-10-21 14:14:21 】 浏览:43
Tags:Sort 函数

原创


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

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇洛谷P2062 分队问题(dp) 下一篇c/c++ 标准容器 之 初始化, 赋值..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目