【问题标题】:Stable sort custom comparator using pass by reference with lamdas gives compile error使用 lamdas 引用传递的稳定排序自定义比较器会产生编译错误
【发布时间】:2020-11-23 20:35:49
【问题描述】:

https://leetcode.com/problems/move-zeroes/ 正在解决这个问题。 但这不会编译。

void moveZeroes(vector<int>& nums) {
    

    stable_sort(nums.begin(), nums.end(),[](int& a, int& b){
            if(a == 0 && b != 0){
                return false;
            }
            if(a != 0 && b == 0){
                return true;
            }
            else {return false;}
        });
    }

但是,如果我们使用按值传递,即 (int a, int b) 它编译。 根本问题是什么??

【问题讨论】:

  • 你的编译器给你什么错误信息?

标签: c++ sorting lambda stl stable-sort


【解决方案1】:

lambda 可以将其参数作为 refs。问题是,在您的示例中,它们不是 const-ref,并且 std::stable_sort 传递 const 值,

补偿

  • [...]
    的签名 比较函数应该等价于:

    bool cmp(const Type1 &a, const Type2 &b);
    

    虽然签名不需要const &amp;,但函数不能修改传递给它的对象,并且必须能够 接受所有类型的值(可能是constType1Type2 无论值类别如何(因此,Type1 &amp; 是不允许的,也不 是Type1,除非对于Type1,移动等价于复制(因为 C++11))。

不能转换为非常量引用。只需声明 lambda 以采用 const int&amp; 代替:

stable_sort(nums.begin(), nums.end(),[](const int& a, const int& b) {
    // ...
  });

编译器错误是一个致命的赠品(为简洁起见,文件名被截断):

bits/predefined_ops.h:177:11: error: no match for call to ‘(moveZeroes(std::vector<int>&)::<lambda(int&, int&)>) (int&, const int&)’
  177 |  { return bool(_M_comp(*__it, __val)); }
      |           ^~~~~~~~~~~~~~~~~~~~~~~~~~~
bits/predefined_ops.h:177:11: note: candidate: ‘bool (*)(int&, int&)’ <conversion>
bits/predefined_ops.h:177:11: note:   conversion of argument 3 would be ill-formed:
bits/predefined_ops.h:177:11: error: binding reference of type ‘int&’ to ‘const int’ discards qualifiers

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-06-05
  • 1970-01-01
  • 1970-01-01
  • 2020-12-04
  • 1970-01-01
  • 1970-01-01
  • 2020-05-06
  • 1970-01-01
相关资源
最近更新 更多