Anirudh Gupta
Anirudh Gupta

Reputation: 201

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];

Upvotes: 3

Views: 274

Answers (3)

Arne J
Arne J

Reputation: 415

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);

Upvotes: 1

Silvano Cerza
Silvano Cerza

Reputation: 970

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.

Upvotes: 1

Bart
Bart

Reputation: 1580

I think m is not known within the context of your lambda. You have to pass it as a capture:

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

Upvotes: 0

Related Questions