有关 sort 排序

---------------------

本文来自 语海与冰 的优快云 博客

---------------------

包含的头文件

#include <algorithm>
        +
using namespace std;

 

1、一维数组排序

#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;

bool cmp(int a,int b)   //如果是double型的,参数改为double a,double b
{
    return a<b;         //升序
} 

int main()
{
    int a[100];
    int i;
    int n;
    scanf("%d",&n);
    for(i=0;i<=n-1;i++)
        scanf("%d",a+i);
    sort(a,a+n,cmp);    //如果不加被调函数名字,sort(a,a+n)代表默认升序排序

    for(i=0;i<=n-1;i++)
        printf("%d ",a[i]);
}

 

2、多个字符串按 字典序 / 字符串长度 排序

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<algorithm>
using namespace std;

bool cmp(char *a,char *b)
{
    return strcmp(a,b)<0;   // 按字典序排序
                    //如果排的是字符串长度 return strlen(a)<strlen(b);
}

int main()
{
    char s[100][100];
    char *p[100];   
    int i;
    int n;
    scanf("%d",&n);
    getchar();
    for(i=0; i<=n-1; i++)
    {
        gets(s[i]);
        p[i]=s[i];
    }
    sort(p,p+n,cmp);

    for(i=0; i<=n-1; i++)
        printf("%s\n",p[i]);
}

 

3、对 string 类型的字符串排序

(1)、 一维

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<string>
#include<algorithm>
using namespace std;

bool cmp(char a,char b)
{
    return a<b;
} 

int main()
{
    string str;
    cin>>str;
    sort(str.begin(),str.end(),cmp);
    cout<<str<<endl;
}

 

(2)、二维

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<string>
#include<algorithm>
using namespace std;

bool cmp(string a,string b)
{
    return a<b;    //如果排的是字符串长度 return a.size()<b.size();
}
int main()
{
    string str[100]; // 定义的是二维的
    int n;
    cin>>n;
    for(int i=0; i<n; i++)
        cin>>str[i];

    sort(str,str+n,cmp);
    for(int i=0; i<n; i++)
        cout<<str[i]<<endl;
}

4、对结构体排序

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct node
{
    int x;
    int y;
}s[100];
bool cmp(struct node p,struct node q) 
{
    if(p.x==q.x)
        return p.y<q.y;
    return p.x<q.x;
}
//如果x相等按照y从小到大排序,否则按照x从小到大排序


int main()
{
    int i;
    int n;
    scanf("%d",&n);
    for(i=0; i<=n-1; i++)
        scanf("%d %d",&s[i].x,&s[i].y);

    sort(s,s+n,cmp);
    for(i=0; i<=n-1; i++)
        printf("%d %d\n",s[i].x,s[i].y);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值