简体   繁体   English

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

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

I'm declaring my std::map and use it below:我正在声明我的 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++ compiles, no error. g++ 编译,没有错误。 Template parameter only requires a type, but no function body is required, passes compilation.模板参数只需要类型,不需要函数体,通过编译。 I was wondering how this empty comparer would behave.我想知道这个空的比较器会如何表现。 On running it:运行时:

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

I only see this error in calling pure virtual function.我只在调用纯虚函数时看到这个错误。 But my code is using stl template, no polymorphism is in place.但是我的代码使用的是 stl 模板,没有多态性。

So is this a c++ design issue, that compilation doesn't check if a function only has declaration but no function body to run?那么这是一个 c++ 设计问题,编译不检查函数是否只有声明但没有函数体可以运行? Plus, how would c++ standard deal with this?另外,c++ 标准将如何处理这个问题?

Appreciate your explanations.感谢您的解释。

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

You declared std::map to use your own comparator whose signature is bool(int, int) , but did not supply a callable functor.您声明std::map使用您自己的比较器,其签名为bool(int, int) ,但未提供可调用函子。

You should declare a real callable object and pass it to constructor so that your map can call it when needed.您应该声明一个真正的可调用对象并将其传递给构造函数,以便您的地图可以在需要时调用它。

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);

The problem is not related to the template argument, but that you did not provide an actual value for it when constructing the map.该问题与模板参数无关,而是您在构建地图时没有为其提供实际值。

Note that in the documentation for the map constructor, there is a const Compare& parameter.请注意,在地图构造函数的文档中,有一个const Compare&参数。 It is via this parameter that you must give a value for your comparator which in this case is a lambda.正是通过这个参数,你必须为你的比较器提供一个值,在这种情况下是一个 lambda。

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

For example:例如:

#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;
    }
}

Outputs:输出:

12,3
3,4

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

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