priority_queue in C++

Level 4224 keystrokes

A priority_queue always keeps its largest element on top, so top() returns 50, then 30 after a pop, and popping until empty prints the rest in descending order.

C++ code

// By default the largest element has the highest priority (a max-heap)
1priority_queue<int> pq;
// Insert in any order; the internal heap is reorganized on each push
2pq.push(30);
3pq.push(10);
4pq.push(50);
5pq.push(20);
// top is the largest value: prints Top: 50
6cout << "Top: " << pq.top() << endl;
// Remove the largest element (50)
7pq.pop();
// The next largest is now on top: prints After pop: 30
8cout << "After pop: " << pq.top() << endl;
// Take elements out until the queue is empty
9while (!pq.empty()) {
// Values come out in descending order: 30 20 10
10 cout << pq.top() << " ";
11 pq.pop();
12}

Output

Top: 50
After pop: 30
30 20 10 
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 17
  • (× 11
  • )× 11
  • ;× 10
  • .× 10
  • "× 6
  • :× 2
  • _× 1
  • !× 1
  • {× 1

More C++ examples at level 4

← C++ typing practice