【发布时间】:2022-04-05 20:18:41
【问题描述】:
我正在寻找一种 c++ 方法,该方法能够按特定列中值的降序对矩阵的行进行排序。
例如,如果这是我的输入:
matrix = [1,2,3;
2,4,1;
0,5,2]
方法(矩阵,3)的调用应该提供以下输出:
outputMatrix = [1,2,3;
0,5,2;
2,4,1]
在 MATLAB 中,这可以通过调用函数来完成:
outputMatrix = sortrows(matrix,3).
c++ 呢? (在这两种情况下,3 都是列的索引)。
此外,在我正在工作的脚本中,矩阵被定义为向量的向量:std::vector<std::vector<double> > matrix
[编辑]我再添加一个例子:
input = [4,5,6;
0,2,8;
1,2,3;
6,7,9]
outputMatrix = sortrows(输入,2); 第 2 列,有序,是:9,8,6,3;所以我必须对行进行排序并复制前两列的元素(分别为 0 和 1)。
outputMatrix = [6,7,9;
0,2,8;
4,5,6;
1,2,3]
我在这里报告我写的方法,但我不知道这是否是一个快速的方法:
std::vector<std::vector<double> > sortrows(std::vector<std::vector<double> > matrix,int col){
int length = matrix[col].size();
std::vector<std::vector<double> > output(3,std::vector<double>(length*length));
output[col] = matrix[col];
std::sort(output[col].begin(),output[col].end(),std::greater<double>());
for (int i = 0; i < length*length;i++){
int index = 0;
while(output[col][i]!=matrix[col][index]){index++;}
output[0][i]=matrix[0][index];
output[1][i]=matrix[1][index];
matrix[2][index] = -1;
}
return output;
}
【问题讨论】:
-
你知道如何实现一些简单的东西,比如一个 int 数组吗?你对
std::sort满意吗? -
感谢您的帮助,无论如何我是 C++ 的新手,我已经阅读了有关仅对向量而非矩阵使用排序的信息。特别是我不知道如何使用条件函数。
-
如果您希望有人为您编写函数,请询问同事。如果你想学习自己写,我建议你先用铅笔和纸在一个小的整数数组上实现Bubble Sort。你必须从简单的开始,爬到复杂的。