You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按指定行对2D vector的所有列进行排序

实现思路
  • 首先生成指定行元素与对应原始列索引的配对序列,避免排序后丢失原始列位置信息
  • 对配对序列按元素值升序排序,提取得到排序后的列索引顺序
  • 遍历二维vector的所有行,按照上面得到的索引顺序重新组装每行元素,得到最终结果
C++ 代码实现
#include <vector>
#include <algorithm>

using namespace std;

vector<vector<int>> sortMatrixByTargetRow(vector<vector<int>> matrix, int targetRow) {
    // 若你传入的是0索引行号,可删除下一行转换逻辑
    targetRow -= 1;
    int colCount = matrix[0].size();

    // 存储<目标行元素值, 原始列索引>
    vector<pair<int, int>> valWithColIdx;
    for (int col = 0; col < colCount; ++col) {
        valWithColIdx.emplace_back(matrix[targetRow][col], col);
    }

    // 按元素值升序排序
    sort(valWithColIdx.begin(), valWithColIdx.end());

    // 提取排序后的列索引序列
    vector<int> sortedColIdx;
    for (auto &item : valWithColIdx) {
        sortedColIdx.push_back(item.second);
    }

    // 按索引重排所有行
    vector<vector<int>> result;
    for (auto &row : matrix) {
        vector<int> newRow;
        for (int idx : sortedColIdx) {
            newRow.push_back(row[idx]);
        }
        result.push_back(newRow);
    }
    return result;
}
示例验证

你给出的测试用例中,传入目标行号为2(1索引),排序后得到的列索引序列为[0,2,1],所有行按该序列取元素即可得到你给出的预期输出。

补充说明
  • 可自行添加入参校验逻辑,比如判断目标行号是否合法、矩阵所有行长度是否一致等,避免运行异常
  • 如果需要按降序排序,只需修改sort的比较规则即可

内容的提问来源于stack exchange,提问作者Ralcive

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 20:06:00