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

C++如何实现二维数组按每个子数组的第二个值排序

C++ 二维数组按子数组第二个元素排序实现方案

核心思路

C++ 标准库<algorithm>提供的std::sort接口支持自定义比较规则,和 Python 中sort指定key参数的逻辑完全对应,仅需在调用时传入对应比较逻辑即可。

针对C风格二维数组的实现(适配你给出的示例代码)

C++11 及以上版本(推荐,支持lambda语法)

#include <iostream>
#include <algorithm>

int main() {
    int exampleArray[5][2] = {
        {4, 20},
        {1, 4},
        {7, 15},
        {8, 8},
        {8, 1}
    };

    // 自定义比较规则:按子数组下标为1的元素升序排列
    std::sort(exampleArray, exampleArray + 5, [](const int (&a)[2], const int (&b)[2]) {
        return a[1] < b[1];
    });

    // 打印验证结果
    for (int i = 0; i < 5; i++) {
        std::cout << "{" << exampleArray[i][0] << ", " << exampleArray[i][1] << "}\n";
    }
    return 0;
}

运行后输出和你要求的排序结果完全一致。

兼容C++11之前的旧版本

如果编译环境不支持lambda语法,单独定义比较函数即可:

#include <iostream>
#include <algorithm>

bool compare(const int a[2], const int b[2]) {
    return a[1] < b[1];
}

int main() {
    int exampleArray[5][2] = {
        {4, 20},
        {1, 4},
        {7, 15},
        {8, 8},
        {8, 1}
    };

    std::sort(exampleArray, exampleArray + 5, compare);

    for (int i = 0; i < 5; i++) {
        std::cout << "{" << exampleArray[i][0] << ", " << exampleArray[i][1] << "}\n";
    }
    return 0;
}

STL容器写法(更符合现代C++编码规范)

如果使用std::vector作为二维数组的实现,写法更简洁:

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

int main() {
    std::vector<std::vector<int>> exampleArray = {
        {4, 20},
        {1, 4},
        {7, 15},
        {8, 8},
        {8, 1}
    };

    std::sort(exampleArray.begin(), exampleArray.end(), [](const auto& a, const auto& b) {
        return a[1] < b[1];
    });

    for (const auto& item : exampleArray) {
        std::cout << "{" << item[0] << ", " << item[1] << "}\n";
    }
    return 0;
}

补充说明

  • 若需要按第二个元素降序排列,只需将比较逻辑中的<替换为>即可
  • 比较函数返回true时代表第一个参数需要排在第二个参数之前,可以根据需求灵活调整排序规则

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 06:57:04