Manika Sharma
Manika Sharma

Reputation: 97

Error: "reference to non static member function must be called" not getting resolved when using classes

I am trying to solve a question, where I have a 2d array of n x 2 . I want to sort the array by second column. I don't want to use manual sorting, and rather I am trying to use STL.

My issue: I am getting the error: "reference to non static member function must be called"

I tried declaring the function, structure outside the class, but then I was resulted in different set of errors. I tried to implement the already present solutions, but I couldn't arrive at a desired solution.

Below is my code:

class Solution {
public:
    
    struct Interval 
    { 
        int column1, column2; 
    };
    
    bool sortcol(Interval i1, Interval i2) 
    { 
        return (i1.column2 < i2.column2); 
    } 
    
    vector<int> kWeakestRows(vector<vector<int>>& mat, int k) {
        
        vector<vector<int> > count( mat.size() , vector<int> (2, 0));
        
        for( int i = 0 ; i < mat.size() ; i++ )
        {
            for( int j = 0 ; j < mat[i].size() ; j++ )
            {
                if(mat[i][j])
                {
                    count[i][1]++;
                }
            }
            
            count[i][0] = i;
        }
    
    sort(count.begin(), count.end(), sortcol); 
        
    vector<int> arr;
    
    for( int i = 0 ; i < mat.size() ; i++ )
    {
        arr.push_back( count[i][0]);
    }
    
        
    return arr;
        
    }
};

Thanks a lot for looking into my problem.

Upvotes: 0

Views: 6838

Answers (1)

Daniel Zin
Daniel Zin

Reputation: 499

The sort algorithm in your case needs "function object" (instance of object having operator() or pointer to function), which accepts references to 2 comparing vectors and returns bool, for example:

// function out of class scope
bool compVectorBySecondElt(const vector<int>& first, const vector<int>& second) {
    return first[1] < second[1]; // hope the index 1 is valid
}

As stated in reply above, your comparator could be "free function, a static member function, or a lambda". Also it could be object of class like:

struct MyVectorCmp {
    bool operator()(const vector<int>& first, const vector<int>& second) {
        return first[1] < second[1]; // hope the index 1 is valid
    }
};

The common side of all these cases is ability to call your functional object with 2 parameters and to accept bool value as result.

In your example you accepted the error because any non-static method of class is not a regular function, besides explicitly specified parameters it could be considered as having additional implicit this parameter, pointing to current object.

Upvotes: 2

Related Questions