如何定义一个自定义比较函数来按照一维数组排序对矩阵进行排序

How to define a custom compare function to sort a matrix according as one dimensional array sort

本文关键字:数组排序 一维 排序 函数 定义 何定义 一个 比较 自定义      更新时间:2023-10-16

我正在尝试排序二维数组(矩阵),而一维数组作为排序相关的行顺序。

如何定义一个合适的比较函数?

(或。我是否应该编写自己的复古风格的冒泡排序函数)

double matrix[4][3];
double id[4];
fillAllArrays();//declared somewhere
std::sort(std::begin(matrix),std::end(matrix),compare);
//how can I define compare function ?

下面的演示显示了输入的两个数组(BEFORE)和我想要排序的东西,就像在(AFTER)节中一样,当我排序id数组值时,矩阵的相关行应该相同地重新排序。

(提前感谢任何回应和想法)

之前
double matrix[4][3]
0.45 0.67 0.41
0.94 0.34 0.34
0.12 0.50 0.42
0.34 0.52 0.74
double id[4]
35
67
12
47


double matrix[4][3]
0.12 0.50 0.42
0.45 0.67 0.41
0.34 0.52 0.74
0.94 0.34 0.34
double id[4]
12
35
47
67

应该避免在排序过程中移动矩阵的行。而是对

的向量进行排序
struct IdAndIndex{ 
    double id;
    int index;
};

包含您的id和数组中的原始索引。一旦你排序了std::vector<IdAndIndex>,你就可以相应地重新排列矩阵行。

或者如果你真的想直接对矩阵排序(可能它很小),你可以对

的向量排序
struct IdAndRow {
    double id;
    double[3] row;
    bool operator<(const IdAndRow& other) { return id < other.id; }
};