简体   繁体   中英

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM