c++ - 优先队列功能比较

标签 c++ boolean compare priority-queue

在下面的代码中,当在优先级队列中使用时,比较项目是被推送的项目吗?
因此,在Mycomp函数中,是否正在添加对象的pair &a和已经在队列中并与之进行比较的pair &b

class Solution {
public:
    
    struct Mycomp {
        bool operator()(const pair<int, string> &a, const pair<int, string> &b){
            
            if(a.first != b.first) { // comparing the frequency if it is not same then return the one with smallest frequency
                return a.first > b.first;
            }else{
                // if frequency are same then compare the alphabetical order - should return the largest one as the idead is to pop smallest frequency with 
                // largest alphabetical order
                return a.second < b. second;
            }
        }
    };

    vector<string> topKFrequent(vector<string>& words, int k) {
        
        //defining a map to keep track of the frequency of the words
        std::unordered_map<string, int> hashMap;

        for( auto word : words) {
            hashMap[word]++;
        }
        
        // Now we use the concept of priority queue 
        std::priority_queue<pair<int, string>,std::vector<pair<int,string>>, Mycomp> pq ;
        
        for(auto ele : hashMap) {
            pq.push({ele.second, ele.first});
            
            if(pq.size() > k) {
                pq.pop(); // pop the elements with least frequency
            }
        }
        
        vector<string> result;
        while(k--){
            result.insert(result.begin(),pq.top().second); // if you use push back, then you need to reverse the vector as pq returns the highest alpabetical order when popping.
            pq.pop();
        }
        
        return result;
    }
};

最佳答案

否。第一个参数不是要添加的对象。operator()的第二个参数,通常是刚添加的对象。
通常,第一个参数是队列的中间元素。
但是同样,在某些情况下,这些行为可能会出乎意料,并取决于所使用的编译器或算法。

关于c++ - 优先队列功能比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62546067/

相关文章:

c++ - 在 C++ 中欺骗 std::cin

java - C++/Java : Toggle boolean statement?

java - 更改 boolean 数组中的值。选择地方而不是值(value)

java - 找出数组类型来比较java中的数组

java - 比较两个不同的音频文件不起作用

c++ - ctime 和 time_t 的数学运算

c++ - 编写 bool 表达式来判断列表是否在增加

c++ - 共享预编译头文件

c# - 按位或 : C# versus C++

perl - 我应该如何比较 Perl 引用文献?