reb*_*oma 1 c++ sorting matrix
我正在寻找一种c ++方法,该方法能够按特定列中的值的降序对矩阵的行进行排序。
例如,如果这是我的输入:
matrix = [1,2,3;
2,4,1;
0,5,2]
Run Code Online (Sandbox Code Playgroud)
方法(matrix,3)的调用应提供以下输出:
outputMatrix = [1,2,3;
0,5,2;
2,4,1]
Run Code Online (Sandbox Code Playgroud)
在MATLAB中,这可以通过调用以下函数来完成:
outputMatrix = sortrows(matrix,3).
Run Code Online (Sandbox Code Playgroud)
那C ++呢?(在两种情况下,3都是列的索引)。
而且在我正在工作的脚本中,矩阵被定义为向量的向量: std::vector<std::vector<double> > matrix
[编辑]我添加另一个示例:
input = [4,5,6;
0,2,8;
1,2,3;
6,7,9]
Run Code Online (Sandbox Code Playgroud)
outputMatrix = sortrows(input,2); 第2列的顺序为:9、8、6、3;因此,我必须对行进行排序并复制前两列的元素(分别为0和1)。
outputMatrix = [6,7,9;
0,2,8;
4,5,6;
1,2,3]
Run Code Online (Sandbox Code Playgroud)
我在这里报告我编写此操作的方法,但是我不知道这是否是一种快速的方法:
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;
}
Run Code Online (Sandbox Code Playgroud)
类似于以下内容(在C ++ 11中),根据特定列对矩阵行进行排序
void sortrows(std::vector<std::vector<double>>& matrix, int col) {
std::sort(matrix.begin(),
matrix.end(),
[col](const std::vector<double>& lhs, const std::vector<double>& rhs) {
return lhs[col] > rhs[col];
});
}
Run Code Online (Sandbox Code Playgroud)
还要注意,此代码更改了原始矩阵,而不是返回新矩阵。
非C ++ 11版本:
class Compare {
public:
Compare(int col) : col_(col) {}
bool operator()(std::vector<double>& lhs, std::vector<double>& rhs) {
return lhs[col_] > rhs[col_];
}
private:
int col_;
};
void sortrows(std::vector<std::vector<double>>& matrix, int col) {
std::sort(matrix.begin(), matrix.end(), Compare(col));
}
Run Code Online (Sandbox Code Playgroud)