您的位置:首页 > 其它

数组结构体中排序

2016-03-17 10:37 281 查看
//sort排序用法
//函数原型: void sort(iterator begin, iterator end);

//将[begin,end) 之间的元素使用默认的<进行排序

#include <algorithm>  // 包含头文件

//自定义排序函数

bool cmp(const int a,const int b)

{     return a > b;}

int main()

{

       int a[5]={3,4,1,2,5};

       sort(a,a+5,cmp);   //cmp,降序排序 5,4,3,2,1

       sort(a,a+5);      //默认升序排序,1,2,3,4,5

       return 0;

}

 

//sort,自定义数据结构

#include <iostream>

#include <algorithm>

using namespace std;

 

struct Node

{

       int x;

       int y;

       bool operator < (const struct Node& a) //重载<号

       {

              return x < a.x;  //按x升序

           //return x >a.x;  //按x降序

       }

}node[10];

int main()

{

       node[0].x = 5;

       node[1].x = 3;

       node[2].x = 4;

       node[3].x = 1;

       node[4].x = 2;

       sort(node,node+5);

       for(int i = 0; i < 5; i++)

       {

              cout<<node[i].x<<endl;   // 1  2  3  4  5

       }

       return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: