使用std::function作为set比较器时触发bad function call异常的解决
问题分析与解决
核心问题1:std::set未正确初始化比较器
你的代码中,_inputSet使用decltype(_lenComp)作为比较器类型,但默认构造的std::set会生成一个空的std::function对象,调用空的std::function必然触发bad_function_call异常。必须在构造函数中把已初始化的_lenComp传递给_inputSet。
核心问题2:比较器不符合严格弱序要求
std::set要求比较器必须满足严格弱序,你当前的lambda逻辑a != b && a.size() >= b.size()不满足规则:
- 当两个字符串长度相等但内容不同时,
a和b互相比较都会返回true,违反了严格弱序的不对称性要求 - 这种无效比较器会导致
std::set的行为完全未定义
修正后的代码
#include <set> #include <string> #include <functional> class Processor { private: // 修正为满足严格弱序的比较器:先按长度降序,长度相同则按字典序升序 const std::function<bool(const std::string&, const std::string&)> _lenComp = [](const std::string& a, const std::string& b) { if (a.size() != b.size()) { return a.size() > b.size(); } return a < b; }; std::set<std::string, decltype(_lenComp)> _inputSet; public: // 修正:在构造函数初始化列表中传入比较器实例 Processor() : _inputSet(_lenComp) { } void addLine(std::string line) { _inputSet.insert(line); } };
关键细节说明
- 传递比较器:在
Processor构造函数的初始化列表中,必须将_lenComp作为参数传给_inputSet的构造函数,确保std::set持有有效的比较器对象 - 严格弱序:修正后的lambda逻辑完全符合严格弱序要求,能保证
std::set的正确工作 - 性能优化:比较器参数使用
const std::string&避免不必要的字符串拷贝,提升代码效率
内容的提问来源于stack exchange,提问作者user1402866
相关产品推荐
相关产品推荐

