Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ priority_queue using map with lambda comparator error

I'm trying to implement my own key comparator for std::proirity_queue as follows:

funtion insertInPQ(vector<int> nums){
   map<int,int> m;
   for(int i=0;i<nums.size();i++)
     m[nums[i]]++;

   auto comp = []( int a, int b ) 
   { 
        return m[a] < m[b]; 
   };
   priority_queue<int, vector<int>, decltype(comp)> pq(comp);
   for(auto it=m.begin();it!=m.end();it++)
        pq.push(it->first);
}

But its giving error:

In lambda function: Line 10: Char 23: error: passing 'const std::map' as 'this' argument discards qualifiers [-fpermissive] return m[a] < m[b];

like image 980
Anirudh Gupta Avatar asked Mar 01 '26 12:03

Anirudh Gupta


2 Answers

First, your capture list of your lambda (the square brackets) is empty, I guess there should be

[&m]

there ?

Next, if you search for the operator[] of std::map, you will find that this can only operate on non-const maps (https://en.cppreference.com/w/cpp/container/map/operator_at). Your lambda is likely being invoked with a const map instead. So try using

return m.at(a) < m.at(b);
like image 152
Arne J Avatar answered Mar 04 '26 01:03

Arne J


You're lamdba is wrong, you either need to compare the two arguments or capture the m variable.

auto comp = []( int a, int b ) 
{ 
     return a < b; 
};

Or:

auto comp = [m]( int a, int b ) 
{ 
     return m[a] < m[b]; 
};

It depends what you want exactly to do.

like image 37
Silvano Cerza Avatar answered Mar 04 '26 01:03

Silvano Cerza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!