Reputation: 201
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
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
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