对结构体数组排序的几种方法:
1. 写外部比较函数

示例代码
#include<iostream>
#include<algorithm>
using namespace std;
struct node {
int x,y;
};
bool comp(const node &a,const node &b)
{
if (a.x!=b.x) return a.x<b.x;
return a.y<b.y;
}
int main()
{
node a[]={{3,2},{2,5},{3,4},{1,3}};
int n=sizeof(a)/sizeof(node);
sort(a,a+n,comp);
for (int i=0;i<n;i++)
cout<<a[i].x<<" "<<a[i].y<<endl;
return 0;
}
2. 写内部比较函数(重载小于号<、大于号>)
a) 非友员函数

示例代码
#include<iostream>
#include<algorithm>
using namespace std;
struct node {
int x,y;
bool operator < (const node &b)const //这里只重载了小于号
{
if (x!=b.x) return x<b.x;
return y<b.y;
}
};
int main()
{
node a[]={{3,2},{2,5},{3,4},{1,3}};
int n=sizeof(a)/sizeof(node);
sort(a,a+n);
for (int i=0;i<n;i++)
cout<<a[i].x<<" "<<a[i].y<<endl;
return 0;
}
b) 友员函数

示例代码
#include<iostream>
#include<algorithm>
using namespace std;
struct node {
int x,y;
friend bool operator < (node a,node b)
{
if (a.x!=b.x) return a.x<b.x;
return a.y<b.y;
}
friend bool operator > (node a,node b)
{
if (a.x!=b.x) return a.x>b.x;
return a.y>b.y;
}
};
int main()
{
node a[]={{3,2},{2,5},{3,4},{1,3}};
int n=sizeof(a)/sizeof(node);
sort(a,a+n,greater<node>());
for (int i=0;i<n;i++)
cout<<a[i].x<<" "<<a[i].y<<endl;
return 0;
}
注意,重载了小于号,可以用less<node>(),重载了大于号,才能用greator<node>() 。默认是小于,less<node>()可以省略。如sort(a,a+n,less<node>())可以写成sort(a,a+n)。
posted on 2014-03-05 17:58
龙在江湖 阅读(503)
评论(0) 编辑 收藏 引用 所属分类:
C++