- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在寻找一种 C++ 方法,它能够按照特定列中值的降序对矩阵的行进行排序。
例如,如果这是我的输入:
matrix = [1,2,3;
2,4,1;
0,5,2]
方法(matrix,3) 的调用应提供以下输出:
outputMatrix = [1,2,3;
0,5,2;
2,4,1]
在 MATLAB 中,这可以通过调用函数来完成:
outputMatrix = sortrows(matrix,3).
C++ 呢? (在这两种情况下,3 都是列的索引)。
此外,在我正在使用的脚本中,矩阵被定义为 vector 的 vector :std::vector<std::vector<double> > matrix
[编辑] 我添加另一个示例:
input = [4,5,6;
0,2,8;
1,2,3;
6,7,9]
输出矩阵 = 排序行(输入,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;
}
最佳答案
类似于下面(在 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];
});
}
另请注意,此代码更改原始矩阵而不是返回新矩阵。
非 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));
}
关于c++方法按列中的元素对矩阵进行排序(与MATLAB中的sortrows相同),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31370380/
我如何为某些排序列使用自定义(即非标准)排序顺序对表的行进行排序? 例如,下面的显示显示了 sortrows 的输出,具有所有排序列的标准排序顺序: >> sortrows(A, {'TrafficL
我的 Android OpenCV 项目中有一个二维数组类型 Mat,我需要按照与 MATLAB sortrows 函数相同的方式对数组进行排序。我发现 Core.sort() 函数采用 Sort_E
我有数据(数字 M x N,n > 2)到达时按第一列排序,然后按第二列排序。有谁知道一种有效的算法可以将数据转换为按第二列然后是第一列排序?显然,sortrows(data,[2,1]) 可以解决问
我是一名优秀的程序员,十分优秀!