为何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
相关产品推荐
相关产品推荐

