c++11 - 为什么在 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;
}
解决方案
您可能正在寻找这样的东西:
class foo {
public:
using Cmp = function<bool(int a, int b)>;
map<int, int, Cmp> rbtree { [](int a, int b){return a > b;} };
};
推荐阅读
- matlab - 从 .mat 文件中的结构中提取数据
- sql - 有没有办法在 SPARK-SQL 中获得这个解决方案,我们需要在记录分组后应用过滤器?
- upgrade - SAP Commerce/Hybris 升级多个版本
- django - 如何使用 django 制作高度可扩展的聊天应用程序?
- c# - C# Telerik winforms radDropDownList 多选
- python - 如何使 python matplotlib 栏从低数字而不是高数字开始?
- javascript - 更改处理程序以避免单击两次要求 - React
- go - 为自定义枚举类型使用标志
- python - Numpy按行索引修改行
- javascript - 在 TabView 内嵌套水平 FlatList(方向相同)