Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: invalid use of member <...> in static member function

I'm encountering this error when I'm trying to use the content of my map 'freq' declared as a class variable, inside my comparator function for sorting the vector(using map to sort the vector elements by frequency). Can anyone highlight where am i going wrong and what should I do? Here's the code:

class Solution {
    map<int, int> freq;
public:
    static bool comp(int a, int b){
        if(a!=b){
            int c1 = freq[a];
            int c2 = freq[b];
            if(c1!=c2)
                return c1<c2;
            else{
                return a>b;
            }
        }
        return a>b;
    }
    vector<int> frequencySort(vector<int>& nums) {
        for(int i:nums){
            freq[i]++;
        }
        sort(nums.begin(), nums.end(), comp);
        return nums;
    }
};

Error is: Line 6: Char 22: error: invalid use of member 'freq' in static member function int c1 = freq[a]; ^~~~

like image 379
Arju Aman Avatar asked Dec 12 '25 23:12

Arju Aman


1 Answers

static functions cannot access member objects. But if you make comp a non-static member function, you can no longer pass it to sort.

A solution is to make comp non-static and wrap it in a lambda in the call to sort, something like:

class Solution {
    map<int, int> freq;
public:
    bool comp(int a, int b){
        if(a!=b){
            int c1 = freq[a];
            int c2 = freq[b];
            if(c1!=c2)
                return c1<c2;
            else{
                return a>b;
            }
        }
        return a>b;
    }
    vector<int> frequencySort(vector<int>& nums) {
        for(int i:nums){
            freq[i]++;
        }
        sort(nums.begin(), nums.end(), [this](int a, int b) { return comp(a,b); });
        return nums;
    }
};
like image 72
LWimsey Avatar answered Dec 14 '25 13:12

LWimsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!