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

不使用vector,用std::sort排序二维数组的编译错误解决问询

解决二维数组用std::sort排序的编译错误问题

嘿,我来帮你搞定这个编译错误!你遇到的问题核心是排序函数的比较器参数类型不匹配,咱们一步步拆解:

错误原因分析

当你对二维数组int arr[10][2]调用std::sort时,数组名arr会隐式转换为指向数组第一个元素的指针——也就是int(*)[2](指向包含2个int的数组的指针)。但你写的cmp函数参数是int*,和实际传递的类型不匹配,编译器无法自动转换,所以抛出了那个初始化错误。

修正方案(两种可选,都不用vector)

方案1:修改比较器的参数类型为指向数组的指针

直接把cmp函数的参数改成匹配的类型,这样就能和std::sort传递的参数对齐:

#include <bits/stdc++.h>
using namespace std;

// 参数改为指向长度为2的int数组的指针
bool cmp(int (*a)[2], int (*b)[2]) {
    if ((*a)[0] == (*b)[0]) {
        return (*a)[1] < (*b)[1];
    } else {
        return (*a)[0] < (*b)[0];
    }
}

int main() {
    int arr[10][2];
    int n = 10;
    for (int i = 0; i < n; i++) {
        scanf(" %d %d", &arr[i][0], &arr[i][1]);
    }
    sort(arr, arr + n, cmp);
    
    // 输出验证结果
    for (int i = 0; i < n; i++) {
        printf("%d %d ", arr[i][0], arr[i][1]);
    }
    return 0;
}

如果觉得指针写法有点绕,也可以用typedef简化类型:

typedef int IntPair[2];
bool cmp(IntPair a, IntPair b) {
    if (a[0] == b[0]) {
        return a[1] < b[1];
    } else {
        return a[0] < b[0];
    }
}

方案2:用Lambda表达式(更简洁,C++11及以上支持)

Lambda可以自动推导参数类型,不用单独写cmp函数,代码更紧凑:

#include <bits/stdc++.h>
using namespace std;

int main() {
    int arr[10][2];
    int n = 10;
    for (int i = 0; i < n; i++) {
        scanf(" %d %d", &arr[i][0], &arr[i][1]);
    }
    
    // 用Lambda作为比较器,自动匹配数组元素类型
    sort(arr, arr + n, [](const auto& a, const auto& b) {
        // 简化写法:三元运算符
        return (a[0] == b[0]) ? (a[1] < b[1]) : (a[0] < b[0]);
    });
    
    // 输出结果
    for (int i = 0; i < n; i++) {
        printf("%d %d ", arr[i][0], arr[i][1]);
    }
    return 0;
}

测试验证

用你给的输入示例3 2 3 1 1 1 2 2 6 6 4 4 5 5 7 7 8 8 9 9运行代码,会输出你期望的结果:1 1 2 2 3 1 3 2 4 4 5 5 6 6 7 7 8 8 9 9。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:32:16