简体   繁体   English

如何使用函数对象作为自定义比较器来访问局部变量而不是在 C++ 中使用 lambda 函数?

[英]how to use a function object as a custom comparator for accessing a local variable instead of using a lambda function in C++?

I am trying to learn priority_queue concept in C++, and I came across this interview question.我正在尝试在 C++ 中学习 priority_queue 的概念,我遇到了这个面试问题。 Although, I managed to solve this problem with a lambda function, I could not figure out how to do the same operation with a custom comparator as a function object (I think it is called as 'functor')虽然,我设法用 lambda 函数解决了这个问题,但我无法弄清楚如何使用自定义比较器作为函数对象执行相同的操作(我认为它被称为“函子”)

I really had a hard time to access 'freq' variable via function object.我真的很难通过函数对象访问“freq”变量。 Is it possible to do this with a function object?是否可以使用函数对象来做到这一点? if it is possible how can I do that?如果可能的话,我该怎么做?

class Solution {
public:
    vector<string> topKFrequent(vector<string>& words, int k) {
        unordered_map<string, int> freq;
        for (const auto &word : words) {
            freq[word]++;
        }

        auto compare = [&freq](const auto &left, const auto &right)
                        {
                            if (freq[left] < freq[right]) {
                                return true;
                            } else if (freq[left] > freq[right]) {
                                return false;
                            }
                            return left > right;
                        };

        priority_queue<string, vector<string>, decltype(compare)> PQ(compare);
        
        for (const auto &iter : freq) {
            PQ.push(iter.first);
        }
        
        vector<string> result;
        
        while (k--) {
            result.push_back(PQ.top());
            PQ.pop();
        }
        
        return result;
    }
};

You can create an object explicitly like this:您可以像这样显式地创建一个对象:

struct // no need to name the type
{ 
    unordered_map<string, int> &freq;  // store variable by reference 

    // write operator()
    bool operator()(const string &left, const string &right) const
    {
             if (freq[left] < freq[right]) {
                 return true;
             } else if (freq[left] > freq[right]) {
                 return false;
             }
             return left > right;
    }
} compare{freq};  // capture freq by reference

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

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