MST

星途 面试题库

面试题:C++中sort对自定义结构体的适配

假设有一个自定义结构体如下:struct Point { int x; int y; }; 现在需要使用C++ STL中的sort算法对Point类型的数组进行排序,排序规则是先按x值升序排列,若x值相同则按y值升序排列,请写出相关代码。
33.6万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>
#include <algorithm>
using namespace std;

struct Point {
    int x;
    int y;
};

// 定义比较函数
bool compare(const Point& a, const Point& b) {
    if (a.x != b.x) {
        return a.x < b.x;
    } else {
        return a.y < b.y;
    }
}

int main() {
    Point points[] = {{3, 4}, {1, 2}, {3, 1}};
    int n = sizeof(points) / sizeof(points[0]);

    sort(points, points + n, compare);

    for (int i = 0; i < n; ++i) {
        cout << "(" << points[i].x << ", " << points[i].y << ") ";
    }
    cout << endl;

    return 0;
}