C++ 中两个坐标点比较大小

方法一(使用C++自带的结构体pair)

C++的标准模板std中已经包含结构体pair,使用方法:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
bool cmp(pair<int, int> a, pair<int, int> b) {

    return a.first < b.first || (a.first == b.first && a.second < b.second);

}
int main() {
    vector<pair<int, int>> myVector;
    pair<int, int> a(3, 4);
    pair<int, int> b(2, 5);
    pair<int, int> c(3, 5);
    myVector.push_back(a);
    myVector.push_back(b);
    myVector.push_back(c);
    sort(myVector.begin(), myVector.end(), cmp);//排序,结合cmp函数
}
 

方法二(自定义坐标点结构体Point)

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Point {
private:
    int x;
    int y;
public:
    Point() {};
    Point(int _x, int _y) { x = _x; y = _y; };
    friend bool operator< (const Point &a, const Point &b) {
        return a.x < b.x || (a.x == b.x && a.y < b.y);
    };
};
int main() {
    vector<Point> myVector;
    Point a(3, 4);
    Point b(2, 5);
    Point c(3, 5);
    myVector.push_back(a);
    myVector.push_back(b);
    myVector.push_back(c);
    sort(myVector.begin(), myVector.end());//排序
}

发布了10 篇原创文章 · 获赞 3 · 访问量 302

猜你喜欢

转载自blog.csdn.net/qq_32227619/article/details/105338274