繁体   English   中英

按结构的给定成员对结构数组进行排序(快速排序)

[英]Sort an array of struct by a given member of the struct (quick sort)

我有一个坐标数组(结构类型向量),我想先按 x 坐标对它们进行排序,然后再按 y 坐标排序。 除了编写两个单独的快速排序函数,有没有办法将成员(x 或 y)作为参数传递,并以此进行排序?

基本上是否有一种类型的轴变量,我可以使用这样的 t[i].axis 表示当轴为 x 时的 x 坐标,以及当其为 y 时的 y 坐标

我的结构:

struct point {
    float x, y;
};

编辑:我通过编写一个比较函数来解决这个问题,该函数基于轴进行比较,但如果有人回答我的问题,我将不胜感激:)

我不完全理解你的问题。 但是如果你想选择你想要排序的结构体的哪个成员,那么你可以使用下面非常简单的函数。

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <iomanip>

struct Point {
    float x{};
    float y{};

    friend std::ostream& operator << (std::ostream& os, const Point& p) {
        return os << "X: " << std::left << std::setw(6) << p.x << "  Y: " << std::setw(6) << p.y << "\n";
    }
};

inline void selectiveSort(std::vector<Point>& vp, float Point::* member) {
    std::sort(vp.begin(), vp.end(), [&](const Point & p1, const Point & p2) { return p1.*member < p2.*member; });
}

int main(void) {
    // Define and initialise vector
    std::vector<Point> points{ {1.0,9.0},{2.0,8.0},{3.0,7.0},{4.0,6.0},{5.0,5.0},{6.0,4.0},{7.0,3.0},{8.0,2.0},{9.0,1.0} };

    // Sort by y and display result
    selectiveSort(points, &Point::y);
    std::copy(points.begin(), points.end(), std::ostream_iterator<Point>(std::cout)); std::cout << "\n";

    // Sort by x and display result
    selectiveSort(points, &Point::x);
    std::copy(points.begin(), points.end(), std::ostream_iterator<Point>(std::cout)); std::cout << "\n";

    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM