通过C ++中的两个字段对结构的std :: vector进行排序

问题描述 投票:0回答:1

我具有std::vector的结构以便存储x0y0值。我希望能够通过从x0y0值较低的点开始对向量项进行排序来对其进行排序。目前,我只能通过仅考虑x0y0值对它们进行排序。

    struct Coordinate
    {
        double x0 = 0.0;
        double x1 = 0.0;

        Coordinate(double paramx0, double paramy0) : x0(paramx0), y0(paramy0) {}
    };

 std::vector<Coordinate> coords;
 std::vector<Coordinate> coords_x;
 std::vector<Coordinate> coords_y;  

    bool compareByLength_x(const Coordinate &a, const Coordinate &b)
    {
        return a.x0 < b.x0;
    }

    bool compareByLength_y(const Coordinate &a, const Coordinate &b)
    {
        return a.y0 < b.y0;
    }

    // ... storing values in the vector and then sort it..

    std::sort(coords.begin(), coords.end(), compareByLength_x);

    for (unsigned int i = 0; i < coords.size(); ++i)
    {
       cout << i << " X[0]: " << coords[i].x0 << " Y[0]: " << coords[i].y0 << endl; 
    }

    cout << "\n" << endl;    
    parallel_y(coords.size(), coords);    
    cout << "\n" <<endl;


    std::sort(coords.begin(), coords.end(), compareByLength_y);

    for (unsigned int i = 0; i < coords.size(); ++i)
    {
       cout << i << " X[0]: " << coords[i].x0 << " Y[0]: " << coords[i].y0 << endl; 
    }

    cout << "\n" << endl;    
    parallel_x(coords.size(), coords);    
    cout << "\n" <<endl;

例如,如果向量包含:

125, 140
125, 32
125, 196
164, 38
10, 38

然后它应该变成:

10, 38
125, 32
125, 140
125, 196
164, 38

首先检查最低的x0值,然后对于相同的x0值,寻找最低的y0值。

我该如何实施?我可以使用一个功能吗?

c++ sorting vector data-structures stdvector
1个回答
0
投票
bool compareByLength_x_and_y(const Coordinate &a, const Coordinate &b) { return a.x0 < b.x0 || (a.x0 == b.x0 && a.y0 < b.y0); }
© www.soinside.com 2019 - 2024. All rights reserved.