I'm still confused about priority queue in STL. Here is the objective I wanna achieve, say: I have a structure called Record, which contains a string word and a int counter. For example: I have many records of these (in the sample program, only 5), now I want to keep top N records(in sample, 3).
I know now that I could overload operator < in Record, and put all records in a vector, and then initialize the priority_queue like:
priority_queue< Record, vector<Record>, less<Record> > myQ (myVec.begin(),myVec.end());
However, as I understood, it's not easy to control the size of vector myVec because it's not sorted as I wanted.
I really don't understand why the following can not work:
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();
}
}
Edit: Thanks for your input, now I got it working.However, I prefer if someone could explain why the first version of operator< overload works, the second one (commented out one) won't work and has a long list of compiler errors.
friend bool operator< (const Record& lhs, const Record& rhs)
{
return lhs.count>rhs.count;
}
/*
bool operator<(const Record& rRecord)
{
return this->count>rRecord.count;
}
*/