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

为什么实现二维数组列升序排序的C++代码运行结果不正确?

问题原因分析
  • 非标准变长数组使用:C++标准未支持直接用变量n/m定义数组长度的写法,属于编译器扩展特性,兼容性差。
  • 仅处理了第0列:代码中只把二维数组的第0列提取到arrayS中排序,完全没有遍历其他m-1列,自然无法实现所有列的排序。
  • 排序边界硬编码错误:冒泡循环的上下限直接写死为9,当输入的行数n不等于9时,要么出现数组越界访问(n<9时),要么排序不完整(n>9时)。
  • 冒泡排序下标越界风险:内层循环j没有限制到n-2,当j=n-1时访问j+1会超出arrayS的有效范围,属于未定义行为。
  • 结果未回写与输出不完整:排序后的列没有写回原二维数组,最终也只输出了第0列的排序结果,没有展示所有列排序后的完整数组。
修正后可运行代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    int n, m;
    cout << "array size: n = ";
    cin >> n;
    cout << "array size: m = ";
    cin >> m;
    // 用标准容器替代非标准变长数组
    vector<vector<int>> array(n, vector<int>(m));
    
    // 输入数组
    for (int z = 0; z < n; z++) {
        for (int a = 0; a < m; a++) {
            cin >> array[z][a];
        }
    }

    // 输出原数组
    cout << "原数组:" << endl;
    for (int y = 0; y < n; y++) {
        for (int i = 0; i < m; i++) {
            cout << array[y][i] << "    ";
        }
        cout << endl;
    }
    cout << "************************************\n";
    cout << "按列升序排序后数组:\n";

    // 遍历每一列单独排序
    for (int col = 0; col < m; col++) {
        // 提取当前列
        vector<int> col_data(n);
        for (int row = 0; row < n; row++) {
            col_data[row] = array[row][col];
        }
        // 标准库升序排序,也可替换为自定义冒泡逻辑
        sort(col_data.begin(), col_data.end());
        // 排序后写回原数组
        for (int row = 0; row < n; row++) {
            array[row][col] = col_data[row];
        }
    }

    // 输出排序后的完整数组
    for (int y = 0; y < n; y++) {
        for (int i = 0; i < m; i++) {
            cout << array[y][i] << "    ";
        }
        cout << endl;
    }
    return 0;
}

如果需要保留你原本的冒泡排序实现,可将上述代码中sort(col_data.begin(), col_data.end());替换为以下逻辑:

int temp;
for (int i = 0; i < n-1; i++) {
    for (int j = 0; j < n - 1 - i; j++) {
        if (col_data[j] > col_data[j+1]) {
            temp = col_data[j];
            col_data[j] = col_data[j+1];
            col_data[j+1] = temp;
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 22:45:03