根据c ++中的特定行对矩阵的列进行排序
Sorting columns of a matrix according to a particular row in c++
有没有一种简单的方法可以根据例如在 c++ 中对矩阵进行排序。第一行,以便所有元素相应地重新排列?
示例:
int matrix[3][3] = { {5,2,4},
{1,7,8},
{9,2,6} };
按第一行排序后如下所示:
{2,4,5},
{7,8,1},
{2,6,9}
我更喜欢使用 sort() 函数,而且我不介意使用向量,如果它能让任务更容易的话。
正如评论所说,按列对矩阵排序比按行排序更容易,因为 std::sort
使用 lambda 函数可以完成前者的工作。
我的建议是按行对列索引进行排序,然后使用排序后的索引重建矩阵:
#include <algorithm>
using namespace std;
const int n = 3; // size of matrix
int sort_by_row = 0; // row to sort by
int original[n][n] = { {5,2,4},
{1,7,8},
{9,2,6} };
int main() {
int col_indices[n];
for (int i = 0; i < n; i++) col_indices[i] = i; // create column indices 0...n-1
sort(col_indices, col_indices + n, [] (const int &a, const int &b) { // sort indices by row
return original[sort_by_row][a] < original[sort_by_row][b];
});
int sorted[n][n]; // rebuild matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
sorted[i][j] = original[i][col_indices[j]];
}
}
}
在此方法中,您仅对矩阵进行一次迭代,而如果对矩阵进行转置、排序,然后将其转回,则对矩阵进行两次迭代(在转置期间)。
有没有一种简单的方法可以根据例如在 c++ 中对矩阵进行排序。第一行,以便所有元素相应地重新排列?
示例:
int matrix[3][3] = { {5,2,4},
{1,7,8},
{9,2,6} };
按第一行排序后如下所示:
{2,4,5},
{7,8,1},
{2,6,9}
我更喜欢使用 sort() 函数,而且我不介意使用向量,如果它能让任务更容易的话。
正如评论所说,按列对矩阵排序比按行排序更容易,因为 std::sort
使用 lambda 函数可以完成前者的工作。
我的建议是按行对列索引进行排序,然后使用排序后的索引重建矩阵:
#include <algorithm>
using namespace std;
const int n = 3; // size of matrix
int sort_by_row = 0; // row to sort by
int original[n][n] = { {5,2,4},
{1,7,8},
{9,2,6} };
int main() {
int col_indices[n];
for (int i = 0; i < n; i++) col_indices[i] = i; // create column indices 0...n-1
sort(col_indices, col_indices + n, [] (const int &a, const int &b) { // sort indices by row
return original[sort_by_row][a] < original[sort_by_row][b];
});
int sorted[n][n]; // rebuild matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
sorted[i][j] = original[i][col_indices[j]];
}
}
}
在此方法中,您仅对矩阵进行一次迭代,而如果对矩阵进行转置、排序,然后将其转回,则对矩阵进行两次迭代(在转置期间)。