繁体   English   中英

c++ std::map 比较函数导致运行时“bad_function_call”

[英]c++ std::map compare function leads to runtime "bad_function_call"

我正在声明我的 std::map 并在下面使用它:

    map<int, int, function<bool (int, int)>> m;
    m.insert(make_pair(12,3));
    m.insert(make_pair(3,4));
    for(auto & p : m){
        cout << p.first << "," << p.second << endl;
    }

g++ 编译,没有错误。 模板参数只需要类型,不需要函数体,通过编译。 我想知道这个空的比较器会如何表现。 运行时:

terminate called after throwing an instance of 'std::bad_function_call'
  what():  bad_function_call

我只在调用纯虚函数时看到这个错误。 但是我的代码使用的是 stl 模板,没有多态性。

那么这是一个 c++ 设计问题,编译不检查函数是否只有声明但没有函数体可以运行? 另外,c++ 标准将如何处理这个问题?

感谢您的解释。

map<int, int, function<bool (int, int)>> m;

您声明std::map使用您自己的比较器,其签名为bool(int, int) ,但未提供可调用函子。

您应该声明一个真正的可调用对象并将其传递给构造函数,以便您的地图可以在需要时调用它。

auto order_by_asc = [](int n1, int n2)->bool {return (n1 < n2); };
std::map<int, int, std::function<bool(int, int)>> m(order_by_asc);

该问题与模板参数无关,而是您在构建地图时没有为其提供实际值。

请注意,在地图构造函数的文档中,有一个const Compare&参数。 正是通过这个参数,你必须为你的比较器提供一个值,在这种情况下是一个 lambda。

explicit map( const Compare& comp,
              const Allocator& alloc = Allocator() );

例如:

#include <functional>
#include <iostream>
#include <map>

using namespace std;

int main()
{
    auto comp = [](int a, int b) { return a > b; };
    map<int, int, function<bool (int, int)>> m(comp);
    m.insert(make_pair(12,3));
    m.insert(make_pair(3,4));
    for(auto & p : m){
        cout << p.first << "," << p.second << endl;
    }
}

输出:

12,3
3,4

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM