首页 > 其他 > 详细

结构体sort()

时间:2018-05-05 16:27:18      阅读:224      评论:0      收藏:0      [点我收藏+]
#include <iostream>
#include <cstdio>
#include <algorithm>//sort要包含的头文件 
#include <time.h>
using namespace std;

struct st
{
    int x,y;
};
st s[10];

bool cmp(st a,st b)//自定义的比较函数 
{
    if (a.x<b.x)//先按第一位数升序排列 
    {
        return true;
    }

    else if (a.x==b.x)
    {
        if (a.y<b.y)//再按第二位数升序排列 
        {
            return true;
        }
    }

    return false;
}

int main()
{
    srand(time(NULL));
    int i;
    for (i=0;i<10;i++)//生成随机数产生样例 
    {
        s[i].x=rand()%10;
        s[i].y=rand()%10;
    }

    for (i=0;i<10;i++)
    {
        printf("%d %d\n",s[i].x,s[i].y);
    }

    printf("\n");
    sort(s,s+10,cmp);// sort默认升序排列 

    for (i=0;i<10;i++)
    {
        printf("%d %d\n",s[i].x,s[i].y);
    }

    return 0;
}

 

结构体sort()

原文:https://www.cnblogs.com/hemeiwolong/p/8994986.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!