首页 > 编程语言 > 详细

结构体排序-c++

时间:2014-12-06 08:50:15      阅读:328      评论:0      收藏:0      [点我收藏+]

功能是先拍a,若a相等则在其基础上对b进行排序。

用的algorithm中sort进行的排序。

#include<iostream>
#include<cstdlib>
#include<algorithm>
using namespace std;
struct test{
    int a;
    int b;
    test():a(0),b(0){}
    test(int x,int y=0):a(x),b(y){}
    set(int x,int y){a=x;b=y;}
};
bool cmp(const test &x,const test &y)
{
    if(x.a != y.a)
        return x.a<y.a;
    else
        return x.b<y.b;
}
int main()
{
    test x[10];
    for(int i=0;i<10;i++)
    {
        int m = rand()%100;
        int n = rand()%100;
        x[i].set(m,n);
    }
    cout<<"before sorted"<<endl;
    for(int i=0;i<10;i++)
    {
        cout<<x[i].a<<" "<<x[i].b<<endl;
    }
    sort(x,x+10,cmp);
    cout<<"after sorted"<<endl;
    for(int i=0;i<10;i++)
    {
        cout<<x[i].a<<" "<<x[i].b<<endl;
    }
    return 0;
}
bubuko.com,布布扣

结构体排序-c++

原文:http://blog.csdn.net/zcliatb/article/details/41772011

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