【问题标题】:C++ priority_queue using map with lambda comparator errorC++ priority_queue 使用带有 lambda 比较器错误的映射
【发布时间】:2019-11-04 08:32:38
【问题描述】:

我正在尝试为 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);
}

但它给出的错误:

在 lambda 函数中: 第 10 行:字符 23:错误:将 'const std::map' 作为 'this' 参数传递会丢弃限定符 [-fpermissive] 返回 m[a]

【问题讨论】:

  • funtion 是 1. 拼写错误和 2. 不是您在 C++ 中声明函数的方式...

标签: c++ dictionary lambda comparator priority-queue


【解决方案1】:

首先,你的 lambda 捕获列表(方括号)是空的,我想应该有

[&m]

那里?

接下来,如果你搜索std::map的operator[],你会发现这个只能对非常量map进行操作(https://en.cppreference.com/w/cpp/container/map/operator_at)。您的 lambda 可能会被 const 映射调用。所以尝试使用

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

【讨论】:

    【解决方案2】:

    你的 lamdba 是错误的,你要么需要比较两个参数,要么捕获 m 变量。

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

    或者:

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

    这取决于你到底想做什么。

    【讨论】:

      【解决方案3】:

      我认为m 在您的 lambda 上下文中是未知的。您必须将其作为capture 传递:

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

      【讨论】:

        猜你喜欢
        • 2011-08-14
        • 1970-01-01
        • 2021-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-17
        • 1970-01-01
        相关资源
        最近更新 更多