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

使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 07:28:24