STL sort function in C++ wrt strings

别来无恙 提交于 2019-12-31 06:59:46

问题


So I've been trying to sort a string based on the frequency of its characters. However the online judge I've been using shows me the error
Line 17: invalid use of non-static member function 'bool olution::helper(char, char)'
Why is the call to my function wrong? I have used the sort() function before, but not to strings. Is my helper() function incorrect?

class Solution {
public:
unordered_map<char,int> freq;

bool helper(char c1,char c2){
    if(freq[c1]>freq[c2]) return false;
    else return true;
}
string frequencySort(string s) {

    for(char c:s)
    {
        freq[c]++;
    }

    sort(s.begin(),s.end(),helper);

    return s;
}
};

回答1:


Use a lambda to capture this:

sort(s.begin(),s.end(),[this](auto a, auto b) -> bool { return helper(a,b); });



回答2:


Why is the call to my function wrong? I have used the sort() function before, but not to strings. Is my 'helper()' function incorrect?

Because helper is member function of Solution. When you do this

sort(s.begin(),s.end(),helper);

you are basically doing this

sort(s.begin(),s.end(),this->helper);

The 3rd parameter to sort needs to be a standalone function, a predicate, a functor or a lambda. It cannnot be a non-static member of a class

This code, cleaned up, works. Note the statics

class Solution {
public:
    // using thread_local so that each thread
    // has its own global variable.
    static thread_local std::unordered_map<char, int> freq;

    static bool helper(char c1, char c2) {
        return (freq[c1]<freq[c2]);
    }

    std::string frequencySort(std::string s)
    {
        freq.clear();

        for (char c : s)
            ++freq[c];

        std::sort(s.begin(), s.end(), helper);

        return s;
    }
};

// definition
std::unordered_map<char, int> Solution::freq;



回答3:


Member functions have a hidden parameter that becomes this. You need either expose the state more widely, or write a capturing lambda

Also a Compare predicate must return false if you are comparing a value to itself, yours does not.

class Solution {
public:
    string frequencySort(string s) {

        unordered_map<char,int> freq;

        for(char c:s)
        {
            freq[c]++;
        }

        sort(s.begin(),s.end(),[&freq](char lhs, char rhs){ return freq[lhs] < freq[rhs]; });

        return s;
    }
};


来源:https://stackoverflow.com/questions/51176716/stl-sort-function-in-c-wrt-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!