简体   繁体   English

使用带有lambda比较器错误的映射的C ++ priority_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: 我正在尝试为std :: proirity_queue实现我自己的关键比较器,如下所示:

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]; 在lambda函数中:第10行:第23行:错误:将'const std :: map'作为'this'参数传递,丢弃限定符[-fpermissive] return m [a] <m [b];

You're lamdba is wrong, you either need to compare the two arguments or capture the m variable. 你是lamdba错了,你需要比较两个参数或捕获m变量。

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 首先,你的lambda捕获列表(方括号)是空的,我想应该有

[&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 ). 接下来,如果你搜索std :: map的operator [],你会发现它只能在非const映射上运行( https://en.cppreference.com/w/cpp/container/map/operator_at ) 。 Your lambda is likely being invoked with a const map instead. 您的lambda很可能是用const映射调用的。 So try using 所以尝试使用

return m.at(a) < m.at(b);

I think m is not known within the context of your lambda. 我认为m是不是你的λ的范围内已知的。 You have to pass it as a capture : 您必须将其作为捕获传递:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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