Search code examples
c++dictionarylambdacomparatorpriority-queue

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


Solution

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