我应该如何纠正这个priority_queue比较功能?

时间:2019-07-19 14:11:59

标签: c++ c++11

使用数字数组nums,我想按其出现的频率对唯一数字进行排序。编译器抱怨传递unordered_map,因为'this'参数丢弃了限定符。我该如何解决?

    void sortByFreq(const vector<int>& nums) {
      unordered_map<int, int> counts;
      for (auto i: nums) ++counts[i];
      auto byCount = [counts](const int& a, const int& b) { return counts[a] > counts[b]; };
      priority_queue<int, vector<int>, decltype(byCount)> minFreq(byCount);
      for (auto& kv: counts) {
        minFreq.push(kv.first);
      }
      ......
    }

3 个答案:

答案 0 :(得分:2)

为什么会有priority_queue?看来我们缺少一些信息。

有几种方法可以解决counts和lambda的问题:

  • 使用at代替operator[]-IMO最佳解决方案
  • 通过引用捕获counts
  • 使lambda可变(我不喜欢这个)

根据您的描述,这应该可以完成工作:

vector<int> sortedByFreq(const vector<int>& nums)
{
    unordered_map<int, int> counts;
    for (auto i : nums)
        ++counts[i];

    vector<int> result = nums;
    std::sort(result.begin(), result.end(),
              [counts](auto a, auto b) {
                  return counts.at(a) > counts.at(b);
              });

    return result;
}

答案 1 :(得分:1)

您需要制作lambda mutable,以允许在复制捕获的counts上调用非常量成员函数。 (请注意,std::unordered_map的{​​{3}}是一个非常量成员函数,如果键不存在,它将执行插入操作。)

  

可变:允许主体修改通过复制捕获的参数,并调用其非常量成员函数

例如

auto byCount = [counts](const int& a, const int& b) mutable { return counts[a] > counts[b]; };

答案 2 :(得分:1)

您可以使用function avgColor(color1, color2) { //separate each color alone (red, green, blue) from the first parameter (color1) //then convert to decimal let color1Decimal = { red: parseInt(color1.slice(0, 2), 16), green: parseInt(color1.slice(2, 4), 16), blue: parseInt(color1.slice(4, 6), 16) } //separate each color alone (red, green, blue) from the second parameter (color2) //then convert to decimal let color2Decimal = { red: parseInt(color2.slice(0, 2), 16), green: parseInt(color2.slice(2, 4), 16), blue: parseInt(color2.slice(4, 6), 16), } // calculate the average of each color (red, green, blue) from each parameter (color1,color2) let color3Decimal = { red: Math.ceil((color1Decimal.red + color2Decimal.red) / 2), green: Math.ceil((color1Decimal.green + color2Decimal.green) / 2), blue: Math.ceil((color1Decimal.blue + color2Decimal.blue) / 2) } //convert the result to hexadecimal and don't forget if the result is one character //then convert it to uppercase let color3Hex = { red: color3Decimal.red.toString(16).padStart(2, '0').toUpperCase(), green: color3Decimal.green.toString(16).padStart(2, '0').toUpperCase(), blue: color3Decimal.blue.toString(16).padStart(2, '0').toUpperCase() } //put the colors (red, green, blue) together to have the output let color3 = color3Hex.red + color3Hex.green + color3Hex.blue return color3 } console.log(avgColor("FF33CC", "3300FF")) // avgColor("FF33CC", "3300FF") => "991AE6" console.log(avgColor("991AE6", "FF0000")) // avgColor("991AE6", "FF0000") => "CC0D73" console.log(avgColor("CC0D73", "0000FF")) // avgColor("CC0D73", "0000FF") => "6607B9" 代替at,因为它具有operator[]限定的过载。

const