【问题标题】:Getting the Error "reference to non-static member function must be called "获取错误“必须调用对非静态成员函数的引用”
【发布时间】:2021-06-20 13:47:07
【问题描述】:

我正在解决 LeetCode 上的一个问题,以进行配对排序并基本上给出输出 链接-https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/

这是我的代码

class Solution {
    public:
    
    bool sortbysec(const pair<int,int> &a,
              const pair<int,int> &b)
    {
        if(a.first == b.first)
            return (a.second < b.second);
        
        return (a.first > b.first);
    }
    
    vector<int> kWeakestRows(vector<vector<int>>& mat, int k) {
        
               
        vector<pair<int,int>>zeros;
        
        vector<int>res;
        
        for(int i = 0;i<mat.size();i++){
            zeros.push_back(make_pair(count(mat[i].begin(),mat[i].end(),0),i)) ;
        }
        sort(zeros.begin(),zeros.end(),sortbysec);
        int n = zeros.size();
        for(int i = 0;i<mat.size();++i){
            res.push_back(zeros[i].second);
        }
        return res;
    }
};

我第一次收到此错误,但不知道 如何解决它

【问题讨论】:

  • sortbysec 是一个非静态成员函数,您不能以这种方式将其作为排序参数传递。
  • 制作sortbysec成员函数static
  • zeros.push_back(make_pair(…, …)) 可以替换为zeros.emplace_back(…, …)

标签: c++ arrays vector


【解决方案1】:

您不能以这种方式将非静态成员函数传递给std::sort,因为它需要Solution 的实例才能调用它。

幸运的是,这种情况下的解决方案很简单:由于sortbysec没有引用任何成员变量,你可以声明它static

static bool sortbysec(const pair<int,int> &a,
          const pair<int,int> &b)

如果您确实需要调用非静态成员函数作为排序函数,您可以通过捕获 lambda 来实现:

sort(zeros.begin(),zeros.end(),
     [this] (const pair<int,int> &a, const pair<int,int> &b) 
         { return sortbysec (a, b); });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多