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

为何C++中此类嵌套容器无法编译?错误原因解析

嵌套容器编译失败的原因分析

你的代码如下:

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

bool cmp(pair<string, int> aa, pair<string, int> bb) {
    return (aa.second == bb.second ? aa.first < bb.first : aa.second > bb.second);
}

int32_t main() {
     map<string, set<pair<string, int>, decltype(cmp)>> store;
}

编译失败的核心原因

  • decltype(cmp)获取的是函数类型bool(pair<string, int>, pair<string, int>),而非函数指针类型。
  • std::set的第二个模板参数要求是可实例化的类型——set内部需要持有该类型的实例来执行比较逻辑,但函数类型本身无法被实例化(你不能直接创建一个函数类型的对象),这直接导致编译器抛出“无效的函数类型”相关错误。

可行的修复方案

方案1:使用函数指针类型

将decltype(cmp)改为decltype(&cmp),同时创建容器时显式传入函数指针(避免默认初始化的空指针导致运行时错误):

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

bool cmp(pair<string, int> aa, pair<string, int> bb) {
    return (aa.second == bb.second ? aa.first < bb.first : aa.second > bb.second);
}

int32_t main() {
     map<string, set<pair<string, int>, decltype(&cmp)>> store(&cmp);
}

方案2:改用仿函数(推荐)

自定义一个重载operator()的结构体,其类型可默认构造,无需额外传递实例:

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

struct Cmp {
    bool operator()(const pair<string, int>& aa, const pair<string, int>& bb) const {
        return (aa.second == bb.second ? aa.first < bb.first : aa.second > bb.second);
    }
};

int32_t main() {
     map<string, set<pair<string, int>, Cmp>> store;
}

方案3:使用无捕获lambda表达式

无捕获lambda的闭包类型是可实例化的,直接用decltype获取其类型即可:

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

int32_t main() {
    auto cmp = [](const pair<string, int>& aa, const pair<string, int>& bb) {
        return (aa.second == bb.second ? aa.first < bb.first : aa.second > bb.second);
    };
    map<string, set<pair<string, int>, decltype(cmp)>> store;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 04:20:25