目录
c++自带的sort函数
使用sort函数对c++结构体进行排序
不用sort函数,直接在结构体内部进行排序
c++自带的sort函数
c++内置一个快速sort函数,默认对数组进行从小到大排序。
sort(a, a + n);
可以通过cmp函数修改排序规则:
bool cmp(int i1,int i2)
{
return b[i1] < b[i2];
}
sort(a, a + n, cmp); //对a数组按照b数组大小进行排序
同时,c++内置两个比较函数less<type>(从小到大排序)和greater<type>(从大到小排序)。可以这样写:
sort(a, a + n, greater<int>());
使用sort函数对c++结构体进行排序
用cmp函数规定排序方法
bool cmp(node i1, node i2)
{
if(i1.x != i2.x)return i1.x < i2.x;
else return i1.y <i2.y;
}
sort(a + 1, a + n + 1, cmp);
通过重载“<”比较运算符规定sort排序方法
struct node
{
int x, y;
friend bool operator < (const node& i1, const node& i2)//友元函数
{
if(i1.x != i2.x)
return i1.x < i2.x;
else return i1.y < i2.y;
}
}a[maxn];
sort(a + 1, a + 1 + n);
不用sort函数,直接在结构体内部进行排序
struct node
{
int x, y;
bool operator < (const node& i) const
{
if(x != i.x)
return x < i.x;
else return y < i.y;
}
}a[maxn];
这个方法排序的速度比sort函数快一点点。