You need to enable JavaScript to run this app. C++如何按指定行对矩阵列排序?能否借助sort()函数实现?
优惠活动
大模型
产品
解决方案
定价
更多

C++如何按指定行对矩阵列排序?能否借助sort()函数实现?

C++ 按指定行排序矩阵列的实现方案

实现该需求最简洁的方式是借助列索引排序+矩阵重组的逻辑,可直接复用标准库sort()函数,使用vector容器实现可适配任意行列数的矩阵,代码量少且不易出错。

核心逻辑

  • 首先生成与矩阵列数等长的列索引数组,初始值为0 ~ 列数-1,对应每一列的原始位置
  • 对索引数组调用sort(),自定义排序规则为「对比指定行中两个索引对应元素的大小」
  • 最后根据排序后的索引数组,按顺序取出原矩阵的对应列,拼接为新矩阵即可

该方案时间复杂度为O(m + nlogn),其中m为矩阵元素总数,n为列数,和直接排序的效率一致。

完整代码示例

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

// 参数说明:mat为待排序矩阵,row_idx为指定排序的行下标(第一行对应下标0)
void sort_matrix_by_row(vector<vector<int>>& mat, int row_idx) {
    int col_cnt = mat[0].size();
    // 初始化列索引数组
    vector<int> col_indices(col_cnt);
    for (int i = 0; i < col_cnt; ++i) {
        col_indices[i] = i;
    }

    // 按指定行的元素值排序列索引
    sort(col_indices.begin(), col_indices.end(), [&](int a, int b) {
        return mat[row_idx][a] < mat[row_idx][b];
        // 如需按降序排序,将上述<改为>即可
    });

    // 按排序后的索引重组矩阵
    vector<vector<int>> sorted_mat(mat.size(), vector<int>(col_cnt));
    for (int new_col = 0; new_col < col_cnt; ++new_col) {
        int old_col = col_indices[new_col];
        for (int row = 0; row < mat.size(); ++row) {
            sorted_mat[row][new_col] = mat[row][old_col];
        }
    }

    mat = move(sorted_mat);
}

int main() {
    // 示例输入矩阵
    vector<vector<int>> matrix = { {5,2,4},
                                   {1,7,8},
                                   {9,2,6} };
    // 按第一行(下标0)排序
    sort_matrix_by_row(matrix, 0);

    // 输出结果
    for (int i = 0; i < matrix.size(); ++i) {
        cout << "{";
        for (int j = 0; j < matrix[i].size(); ++j) {
            if (j != 0) cout << ",";
            cout << matrix[i][j];
        }
        cout << "}" << (i == matrix.size()-1 ? "\n" : ",\n");
    }
    return 0;
}

运行结果

{2,4,5},
{7,8,1},
{2,6,9}

其他说明

如果使用原生二维数组实现,逻辑完全一致,仅需要提前固定矩阵的行列尺寸,灵活度低于vector方案。


内容的提问来源于stack exchange,提问作者Szymon Żurawski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 14:51:03