结构体的排序

结构体非常的强啊,毕竟与class差一点(蒟蒻的理解),可以定义成员变量、成员函数,也可以被直接赋值、被swap交换。但是不能直接调用sort来进行交换,但自定义比较规则就可以了(这也是不能直接使用的原因)

有以下两种方法:

重载运算符“<”

由前面重载运算符的知识,重载函数可写成成员函数,也可以写成普通的非成员函数,这里以成员函数为例

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<algorithm>
 4 using namespace std;
 5 
 6 struct Point
 7 {
 8     int x, y, w;
 9     Point(int _x = 0, int _y = 0, int _w = 0) :x(_x), y(_y), w(_w) {};
10     bool operator < (const Point& p)
11     {
12         return this->x < p.x;            //根据x排序,x小的排前面
13     }
14 };
15 
16 istream& operator >> (istream& in, Point& a)
17 {
18     in >> a.x >> a.y >> a.w;
19     return in;
20 }
21 
22 ostream& operator << (ostream& out, const Point& a)
23 {
24     out << a.x << " " << a.y << " " << a.w;
25     return out;
26 }
27 
28 
29 int main()
30 {
31     int n;
32     Point  points[10];
33     scanf("%d", &n);
34     for (int i = 0; i < n; i++)
35         cin >> points[i];
36     sort(points, points + n);        
37     for (int i = 0; i < n; i++)
38         cout << points[i] << endl;
39     
40     return 0;
41 }

利用比较函数作sort的参数

自己写一个cmp函数

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;

struct Point
{
    int x, y, w;
    Point(int _x = 0, int _y = 0, int _w = 0) :x(_x), y(_y), w(_w) {};
};

istream& operator >> (istream& in, Point& a)
{
    in >> a.x >> a.y >> a.w;
    return in;
}

ostream& operator << (ostream& out, const Point& a)
{
    out << a.x << " " << a.y << " " << a.w;
    return out;
}

bool cmp(const Point& a, const Point& b)        //逐位比较,小的排前面
{
    if (a.x == b.x)  return a.y == b.y ? a.w < b.w : a.y < b.y;
    else  return  a.x < b.x;
}

int main()
{
    int n;
    Point  points[10];
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
        cin >> points[i];
    sort(points, points + n,cmp);        
    for (int i = 0; i < n; i++)
        cout << points[i] << endl;
    
    return 0;
}

注:当自定义比较函数和重载<同时存在时,优先使用自定义比较函数(至少我测试是这样

参考资料:https://blog.csdn.net/martinue/article/details/51758888

猜你喜欢

转载自www.cnblogs.com/lfri/p/10087857.html
今日推荐