首页 > 试题广场 >

对struct进行排序

[编程题]对struct进行排序
  • 热度指数:46 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定以下Point类,为其定义小于符号的操作符重载,使得我们可以用std::sort来对vector<Point>进行从小到大的排序(先按x从小到大排,然后按照y从小到大排),确保以下代码成功运行:

#include <iostream>
#include <vector>
#include <algorithm>

struct Point {
    int x;
    int y;
};

int main() {
        int x = 0;
        int y = 0;
        std::vector<Point> vec;
        while (std::cin >> x >> y) {
                Point p;
                p.x = x;
                p.y = y;
                vec.push_back(p);
        }

        std::sort(vec.begin(), vec.end());

        for (auto iter = vec.begin(); iter != vec.end(); ++iter) {
                std::cout << iter->x << " " << iter->y << std::endl;
        }

        return 0;
}


输入描述:
点的集合,一个点一行,每个点由x,y两个整数组成,x和y之间用空格分隔


输出描述:
输出格式和输入格式相同,但已经按从小到大排好序了
示例1

输入

4 6
3 8
4 2
9 6
8 3
9 8

输出

3 8
4 2
4 6
8 3
9 6
9 8
#include <iostream>
#include <vector>
#include <algorithm>

struct Point {
    int x;
    int y;
    
    bool operator <(const Point pt) const {
        if (x != pt.x) {
            return x < pt.x;
        } else {
            return y < pt.y;
        }
        
    }
};

int main() {
        int x = 0;
        int y = 0;
        std::vector<Point> vec;
        while (std::cin >> x >> y) {
                Point p;
                p.x = x;
                p.y = y;
                vec.push_back(p);
        }

        std::sort(vec.begin(), vec.end());

        for (auto iter = vec.begin(); iter != vec.end(); ++iter) {
                std::cout << iter->x << " " << iter->y << std::endl;
        }

        return 0;
}
发表于 2022-10-31 21:48:21 回复(0)