【问题标题】:bad_function_call when using lambda function on boost:heap在 boost:heap 上使用 lambda 函数时的 bad_function_call
【发布时间】:2019-06-05 21:43:58
【问题描述】:

我想创建一个能够更新值的堆数据结构。 但是我下面的简单代码会引发异常。为什么它给出以下内容:
109 : 3 terminate called after throwing an instance of 'std::bad_function_call' what(): bad_function_call

#include <set>
#include <algorithm>
#include <functional>

#include <boost/heap/fibonacci_heap.hpp>

int main() {

    // Creating & Initializing a map of String & Ints
    std::map<int, vector<int> > mapOfWordCount = { { 1000, {0,1,10,8} },  { 10001, {1,5,99} },  { 1008, {7,4,1} } ,  { 109, {1,5,3} }};

    // Declaring the type of Predicate that accepts 2 pairs and return a bool
    typedef std::function<bool(std::pair<int, vector<int> > v1, std::pair<int, vector<int> > v2)> Comparator;

    // Defining a lambda function to compare two pairs. It will compare two pairs using second field
    Comparator compFunctor = 
        [](std::pair<int, vector<int> > elem1 ,std::pair<int, vector<int> > elem2)
        {
            return elem1.second.size() > elem2.second.size();
        };

    boost::heap::fibonacci_heap <std::pair<int, vector<int> >, boost::heap::compare<Comparator> > pq;
    typedef boost::heap::fibonacci_heap< std::pair<int, vector<int> >, boost::heap::compare<Comparator> >::handle_type handle_t;

    handle_t* tab_handle = new handle_t [mapOfWordCount.size()];
    unsigned iter(0);
    for( auto& element : mapOfWordCount) {
        tab_handle[iter++]=pq.push(element);
        std::cout << element.first << " : " << element.second.size() << std::endl;
    }
}

【问题讨论】:

  • 你已经定义了compFunctor - 但你实际上并没有在任何地方使用它。

标签: c++11 boost lambda functor


【解决方案1】:

std::bad_function_call 在调用空的std::function 时导致(在这种情况下)异常。

我通过使 Comparator 成为仿函数来完成这项工作。

struct Comparator
{
    bool operator()(std::pair<int, std::vector<int> > elem1, std::pair<int, std::vector<int> > elem2) const
    {
        return elem1.second.size() > elem2.second.size();
    }
};

然后可以在pqhandle_t 的声明中使用。

输出:

109 : 3  
1000 : 4  
1008 : 3  
10001 : 3  

查看演示here

您可以弄清楚如何使其与 lambda 一起使用。
提示:它涉及使用 lambda compFunctor 作为构造参数。

【讨论】:

猜你喜欢
  • 2015-01-31
  • 1970-01-01
  • 2016-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-20
相关资源
最近更新 更多