I am still confused in the priority queue in STL. Here is the goal I want to achieve, say: I have a structure called "Record" that contains a string word and an int counter. For example: I have a lot of records about them (in the sample program there are only 5), now I want to save the top N records (in example 3).
Now I know that I can overload the <operator in the records and put all the records in the vector, and then initialize priority_queue as:
priority_queue< Record, vector<Record>, less<Record> > myQ (myVec.begin(),myVec.end());
However, as I understand it, managing the size of the vector myVec is not easy, because it does not sort as I wanted.
I really don't understand why the following cannot work:
struct Record { string word; int count; Record(string _word, int _count): word(_word), count(_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 his job. However, I prefer that someone can explain why the first version of the operator <overload works, the second (commented) will not work and has a long list of compiler errors.
friend bool operator< (const Record& lhs, const Record& rhs) { return lhs.count>rhs.count; }
c ++ initialization vector stl priority-queue
WilliamLou Oct 27 2018-11-11T00: 00Z
source share