bad_function_call在 boost:heap 上使用 lambda 函数时



我想创建一个堆数据结构以便能够更新值。但是我下面的简单代码抛出了一个异常。为什么它会给出以下内容:
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;
    }
}
调用空

std::function时会导致std::bad_function_call异常(在本例中)。

我通过使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  

在此处查看演示。

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

最新更新