C++ priority_queue with lambda comparator error

前端 未结 4 1038
时光说笑
时光说笑 2020-11-30 21:59

I have the following erroneous code which I am trying to compile in VC2010, but I\'m getting the error C2974 this only occurs when I include the lambda expression, so I\'m g

4条回答
  •  天涯浪人
    2020-11-30 22:18

    The accepted answer answered how to define a priority_queue with lambda expression as a custom Compare object. I would address another aspect of the question: why it fails when define a pq in your way:

    typedef pair, int> adjlist_edge;
    priority_queue< adjlist_edge , vector,
        [](adjlist_edge a, adjlist_edge b) -> bool {
            if(a.second > b.second){ return true; } else { return false; }}> adjlist_pq;
    

    Why we MUST pass the lambda as a parameter when constructing the priority queue? The reason lies in that lambda expression does not have a default constructor. So if you does not provide it when constructing the priority queue, the "supposed existing default constructor" of the lambda expression will be called. Clearly, it would fail.

    With regard to your question: it is whether the Compare object(lambda or function object) has a default constructor makes the difference.

提交回复
热议问题