Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ priority_queue with lambda comparator error

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 guessing it has something to do with that.

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

I know the form of the template definition is correct as

priority_queue<int , vector<int>, greater<int>> pq; 

Works as expected. Any ideas what I'm doing wrong? Is there something obviously wrong with the lambda that looks wrong that I might be overlooking? Thanks for reading!

like image 950
ameer Avatar asked Apr 27 '11 16:04

ameer


2 Answers

First define the lambda object, then pass it to the template's type using decltype and also pass it directly to the constructor.

auto comp = []( adjist a, adjlist b ) { return a.second > b.second; }; priority_queue< adjlist_edge , vector<adjlist_edge>, decltype( comp ) >      adjlist_pq( comp ); 
like image 193
Potatoswatter Avatar answered Sep 23 '22 12:09

Potatoswatter


priority_queue takes the comparator as a template argument. Lambda functions are objects, and thus can't be used as template arguments (only very few types can be, among them integral types).

You can try using decltype there:

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

Failing that (and it will), you can use function<>:

priority_queue< adjlist_edge , vector<adjlist_edge>,                 function<bool(adjlist_edge,adjlist_edge)> > adjlist_pq( [](adjlist_edge a, adjlist_edge b) -> bool {                 if(a.second > b.second){ return true; } else { return false; }             } ); 
like image 28
Marc Mutz - mmutz Avatar answered Sep 25 '22 12:09

Marc Mutz - mmutz