c++ - 对非静态成员的引用应称为

标签 c++

class Solution {
public:

    bool comp(int &a,int &b){
        return a>b;
    }

    int findKthLargest(vector<int>& nums, int k) {
        vector<int> vec= nums;
        sort(vec.begin(),vec.end(),comp);  //error: reference to non-static member should be called

        cout << vec[k-1];
    }
};

此错误的原因是什么?我该如何解决呢?

最佳答案

问题在于您要将成员函数传递给std::sort,并且由于它是成员函数,因此需要实例来对其进行调用。

您有一些解决方案。

  • 传递非成员函数。这可以只是一个自由函数,也可以是静态函数
  • 使用lambda。
  • sort(vec.begin(),vec.end(), [this](int i, int j){return comp(i,j);});
    
  • 使用std::bind。
  • sort(vec.begin(), vec.end(), std::bind(&Solution::comp, this, _1, _2));
    
  • 使用标准库比较功能对象。
  • sort(vec.begin(), vec.end(), std::greater<int>());
    
  • 使用自定义函数对象
  •  struct {
         bool operator()(int a, int b) const
         {   
             return a > b;
         }   
     } comp;
     .
     .
     sort(vec.begin(), vec.end(), comp);
    

    附言:
    正如其他人已经指出的那样,没有必要在comp中使用引用,并确保在findKthLargest函数中您实际上返回了一些东西。

    关于c++ - 对非静态成员的引用应称为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61995188/

    相关文章:

    c++ - 如何避免复制构造返回值

    c++ - GNU Automake - 构建与其依赖项静态链接的动态库

    c++ - 用 d&c 方法求解方程

    c++ - 将透明图标加载到应用程序的托盘菜单

    c++ - 大括号初始化列表中的对象创建顺序

    时间:2019-03-08 标签:c++typeidoperator

    c++ - 输入操作

    c++ - 数组错误 - 读取位置 0xffffffff 的访问冲突

    c++ - CString 用于静态方法

    c++ - 将 fork() 与 boost::asio::ip::tcp::iostream 一起使用是否安全?