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

C++如何按子数组首元素对二维数组正确排序

问题原因

你原有代码报错的核心原因有两个:

  • 比较器greater<int>()仅支持单个int值的大小比较,但umbrellas的待排序元素是int[2]类型的长度为2的数组,比较器和待比较元素类型不匹配,直接触发编译错误。
  • 你需要的是按子数组首元素升序排列,greater<int>()实现的是降序比较逻辑,排序方向也不符合需求。
正确实现

自定义比较规则,明确指定按子数组首元素做升序比较即可,可直接运行的示例代码如下:

#include <algorithm>

int main() {
    int umbrellas[3][2] = {{5, 6}, {2, 7}, {9, 20}};
    int n = sizeof(umbrellas) / sizeof(umbrellas[0]);

    // 传入lambda作为比较器,按子数组首元素升序排序
    std::sort(umbrellas, umbrellas + n, [](const int* a, const int* b) {
        return a[0] < b[0];
    });

    // 排序后数组即为 {{2,7}, {5,6}, {9,20}},符合预期
    return 0;
}

如果使用C++11之前不支持lambda的版本,可以单独定义比较函数传入:

bool cmpArr(const int* a, const int* b) {
    return a[0] < b[0];
}

// sort调用方式
std::sort(umbrellas, umbrellas + n, cmpArr);

注意:使用sort函数必须提前引入头文件<algorithm>,否则会触发函数未定义错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 03:01:08