如何定义一个自定义比较函数来按照一维数组排序对矩阵进行排序
How to define a custom compare function to sort a matrix according as one dimensional array sort
我正在尝试排序二维数组(矩阵),而一维数组作为排序相关的行顺序。
如何定义一个合适的比较函数?
(或。我是否应该编写自己的复古风格的冒泡排序函数)
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; }
};
相关文章:
- C++使用数组作为多维数组,尽管将其初始化为带有指针的 1D
- 显示错误输出的简单数组排序程序
- 可以将两个相同类型的连续数组视为一个数组吗?
- 如何将 numpy 二维数组作为一种可以用C++读取的二进制格式存储在磁盘上
- C 使用单个函数对具有多种值类型的数组排序
- 2D数组排序,空格打乱顺序
- 如何使用一维数组更改二维数组中的值?
- 使用二维数组作为一维数组是否正确?可能会导致未定义的行为左右?
- C++ 中的多维数组排序
- 将一维数组视为二维数组
- C++:二维指针数组排序:选择排序不适用于某些实例
- 将一行二维数组分配给一维数组
- 将一维"flattened"索引转换为 N 维数组的 N 维向量索引
- 在编译时推导出二维数组的一维
- 是在内存中连续设置的二维数组,类似于模拟二维数组的一维数组
- 多维数组排序c++奇怪行为
- 如何使用一个动态创建的一维数组的二维数组引用仅与标准库?
- 如何定义一个自定义比较函数来按照一维数组排序对矩阵进行排序
- 二维锯齿数组到一维数组的c++
- 高维数组vs一维数组在c++中的效率