首页 > 解决方案 > 为什么在 std::map 中使用 std::function 作为比较函数对象时出现 bad_function_call 异常

问题描述

当我执行下面的代码时,我得到一个 std::__1::bad_function_call: std::exception 。

我尝试在构造函数中初始化 std::function 并在定义为类变量时直接初始化它。在这两种情况下,我都会遇到上述异常。

请注意,如果我定义了一个函数对象(一个定义了 bool operator () 函数的类),则代码可以正常工作。如何将 lambda 捕获到 std::function 中,以免引发异常?另外,是什么导致下面代码中的异常?

#include <map>
using namespace std;

class foo {
public:
    foo() {cmp = [](const int &a, const int &b){return a > b;};}
    //function<bool(const int &a, const int &b)> cmp = [](const int &a, const int &b){return a > b;};
    function<bool(const int &a, const int &b)> cmp;
    map<int, int, decltype(cmp)> rbtree;
};

int main() {

  foo* obj = new foo();
  obj->rbtree[5] = 5;
  obj->rbtree[1] = 5;
  obj->rbtree[5] = 5;
}

标签: c++11

解决方案


您可能正在寻找这样的东西:

class foo {
public:
    using Cmp = function<bool(int a, int b)>;
    map<int, int, Cmp> rbtree { [](int a, int b){return a > b;} };
};

演示


推荐阅读