我对STL中的优先队列仍然感到困惑。这是我想要实现的目标:我有一个名为Record的结构体,其中包含一个字符串word和一个整型counter。比如说:我有很多这样的记录(在示例程序中只有5个),现在我想要保留前N个记录(在示例中为3个)。
我现在知道可以在Record中重载运算符<,将所有记录放入一个向量中,然后像这样初始化优先队列:
priority_queue< Record, vector<Record>, less<Record> > myQ (myVec.begin(),myVec.end());
然而,据我所知,控制向量 myVec 的大小不容易,因为它不像我想要的那样排序。
我真的不明白为什么以下内容不能起作用:
struct Record
{
string word;
int count;
Record(string _word, int _count): word(_word), count(_count) { };
/*
bool operator<(const Record& rr)
{
return this->count>rr.count;
}
*/
bool operator() (const Record& lhs, const Record& rhs)
{
return lhs.count>rhs.count;
}
};
void test_minHeap()
{
priority_queue<Record> myQ;
Record arr_rd[] = {Record("William", 8),
Record("Helen", 4),
Record("Peter", 81),
Record("Jack", 33),
Record("Jeff", 64)};
for(int i = 0; i < 5; i++)
{
if(myQ.size() < 3)
{
myQ.push(arr_rd[i]);
}
else
{
if(myQ.top().count > arr_rd[i].count)
continue;
else
{
myQ.pop();
myQ.push(arr_rd[i]);
}
}
}
while(!myQ.empty())
{
cout << myQ.top().word << "--" << myQ.top().count << endl;
myQ.pop();
}
}
编辑:感谢您的帮助,现在我的程序能正常工作了。然而,我更希望有人能够解释为什么第一个版本的operator<重载可以工作,而第二个版本(被注释掉的那个)不能正常工作,并输出了一堆编译错误。
friend bool operator< (const Record& lhs, const Record& rhs)
{
return lhs.count>rhs.count;
}
/*
bool operator<(const Record& rRecord)
{
return this->count>rRecord.count;
}
*/
Record
重载operator<
- 它被注释掉了。 - Björn Pollex