问题描述
我正在尝试为我的priority_queue创建仿函数作为自定义比较器,该函数将unordered_map用作构造函数的参数。我不确定在声明priority_queue时如何调用函子,因为出现错误:
“第22行:字符48:错误:模板类型参数的模板参数必须为类型 priority_queue pq;“
class compareWords{
public:
compareWords(unordered_map<string,int> &wordCounts): wordFreq(wordCounts){}
bool operator()(string word1,string word2){
if(wordFreq[word1] == wordFreq[word2]){
return word1 < word2;
}
return wordFreq[word1] < wordFreq[word2];
}
private:
unordered_map<string,int> wordFreq;
};
vector<string> topKFrequent(vector<string>& words,int k) {
vector<string> result;
unordered_map<string,int> wordFreq;
for(int i = 0; i < words.size(); i++){
wordFreq[words[i]]++;
}
priority_queue<string,vector<string>,compareWords(wordFreq)> pq;
for(auto& item: wordFreq){
pq.push(item.first);
}
for(int i = 0; i < k; i++){
result.push_back(pq.top());
pq.pop();
}
return result;
}
解决方法
TL; DR版本:
priority_queue<string,vector<string>,compareWords> pq(compareWords{wordFreq});
我们如何到达那里:
使用简单的解决方案,将比较器传递到pq
的构造函数中,您会遇到Most Vexing Parse和
priority_queue<string,compareWords> pq(compareWords(wordFreq));
^class goes here ^ object goes here
是一个函数定义。 uck通常,MVP的解决方案是使用“统一初始化”
priority_queue<string,compareWords> pq{compareWords(wordFreq)};
^ ^
但这会触发priority_queue
的初始化列表构造函数。还好吧。
但是,我们可以在compareWords
的结构上使用花括号
priority_queue<string,compareWords> pq(compareWords{wordFreq});
^ ^
并避免priority_queue
的初始化列表构造函数重载,同时不要让构造函数认为我们在声明一个函数。感谢Caleth指出这个技巧。我忽略了它。