- C++17 STL Cookbook
- Jacek Galowicz
- 274字
- 2025-04-04 19:00:07
How it works...
The std::priority list is very easy to use. We have only used three functions:
- The q.push(item) pushes an item into the queue.
- The q.top() returns a reference to the item which is coming out of the queue first.
- The q.pop() removes the frontmost item in the queue.
But how did the item ordering work? We grouped a priority integer and a to-do item description string into an std::pair and got automatic ordering. If we have an std::pair<int, std::string> instance p, we can write p.first to access the integer part, and p.second to access the string part. We did that in the loop which prints out all to-do items.
But how did the priority queue infer that {2, "do homework"} is more important than {0, "watch tv"}, without us telling it to compare the numeric part?
The comparison operator < handles different cases. Let's assume we compare left < right and left and right are pairs.
- The left.first != right.first, then it returns left.first < right.first.
- The left.first == right.first, then it returns left.second < right.second.
This way, we can order the items as we need. The only important thing is that the priority is the first member of the pair, and the description is the second member of the pair. Otherwise, std::priority_queue would order the items in a way where it looks like the alphabetic order of the items is more important than their priorities. (In that case, watch TV would be suggested as the first thing to do, and do homework some time later. That would at least be great for those of us who are lazy!)