简体   繁体   English

C ++ WRT字符串中的STL排序功能

[英]STL sort function in C++ wrt strings

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. 我以前使用过sort()函数,但没有使用过字符串。 Is my helper() function incorrect? 我的helper()函数不正确吗?

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;
}
};

使用lambda捕获this

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

Why is the call to my function wrong? 为什么我的函数调用错误? I have used the sort() function before, but not to strings. 我以前使用过sort()函数,但没有使用过字符串。 Is my 'helper()' function incorrect? 我的'helper()'函数不正确吗?

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. 要排序的第三个参数必须是独立函数,谓词,函子或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;

Member functions have a hidden parameter that becomes this . 成员函数具有一个变为this的隐藏参数。 You need either expose the state more widely, or write a capturing lambda 您需要更广泛地公开状态,或者编写捕获lambda

Also a Compare predicate must return false if you are comparing a value to itself, yours does not. 同样,如果您将一个值与自身进行比较,则比较谓词也必须返回false,否则不会。

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;
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM