C++ STL Container Fundamentals: Priority Queue

Last updated by on Sep 25, 2024 at 10:58 PM
Contents

The Standard Template Library (STL) in C++ is a powerful software library that’s a set of C++ template classes. It provides built-in algorithms, functions, iterators, and containers. This article focuses on the C++ STL container priority_queue.

STL containers are objects that can store multiple elements, manage any storage required for the elements, and offer member functions we can use to access them. A container may allow elements of either the same type or different types to be stored in it. Depending on this, and on whether it is unordered, the containers are divided into three types:

  • Sequence Containers: deque, arrays, vector, list, and forward_list
  • Associative Containers: set, multiset, map, and multimap
  • Unordered Associative Containers: unordered_set, unordered_multiset, unordered_map, and unordered_multimap

To help you harness the power of STL and be a more efficient developer, we’re doing a series on C++ STL container fundamentals. This article focuses on the C++ STL container, priority queue (check out the learn page for more). 

Having trained over 11,000 software engineers, we know what it takes to crack the toughest tech interviews. Our alums consistently land offers from FAANG+ companies. The highest ever offer received by an IK alum is a whopping $1.267 Million!

At IK, you get the unique opportunity to learn from expert instructors who are hiring managers and tech leads at Google, Facebook, Apple, and other top Silicon Valley tech companies.

Want to nail your next tech interview? Sign up for our FREE Webinar.

In this article, we’ll cover:

  • C++ STL Container Fundamentals: priority_queue
  • Use of the C++ STL Container priority_queue
  • Methods of priority_queue
  • How to Use the C++ STL Container priority_queue
  • FAQs on C++ STL Container Fundamentals: priority_queue

C++ STL Container Fundamentals: priority_queue

Priority queues in STL are container adapters like regular queues, but the queue elements also have priorities associated with them. They are designed such that we have a max heap maintained by default. 

In a max heap priority queue, the first element of the queue is the largest of all queue elements, and the elements are in nonincreasing order. This means each element of the queue has a priority or a fixed order. We can also create a min-heap for the priority queue by specifying the comparison type.

Use of the C++ STL Container priority_queue

Priority queues are used widely for problems involving:

  • Maps: the shortest path must have the highest priority
  • Emergency queue
  • OS load balancing 
  • Interrupt handling
  • Data compression
  • Traffic lights

Methods of priority_queue

Here are the several methods associated with priority_queue in STL:

  • priority_queue::empty()
  • priority_queue::size() 
  • priority_queue::top()
  • priority_queue::push() 
  • priority_queue::pop()
  • priority_queue::swap()
  • priority_queue::emplace()

Let us now see what some of the most commonly used priority_queue methods do and how to use them in the next section via an example.

How to Use the C++ STL Container priority_queue

Here, we take a look at how you can use priority_queue as a C++ STL container for a smoother coding experience:

C++ STL Priority Queue Example Code


// C++ Queue in STL

#include 
#include 

using namespace std;

// Print the queue
void printPriorityQueue(priority_queue  PQ) {
  priority_queue  priorityQueueToPrint = PQ;
  while (!priorityQueueToPrint.empty()) {
    cout << " " << priorityQueueToPrint.top();
    priorityQueueToPrint.pop();
  }
  cout << "n";
}

void printPriorityQueueMinHeap(priority_queue < int, vector  , greater  > PQ) {
  priority_queue < int, vector  , greater  > priorityQueueToPrint = PQ;
  while (!priorityQueueToPrint.empty()) {
    cout << " " << priorityQueueToPrint.top();
    priorityQueueToPrint.pop();
  }
  cout << "n";
}

int main() {
  priority_queue  intPriorityQueueExample;
  intPriorityQueueExample.push(2);
  intPriorityQueueExample.push(4);
  intPriorityQueueExample.push(6);
  intPriorityQueueExample.push(8);

  cout << "The priority queue intPriorityQueueExample contains (max heap):";
  printPriorityQueue(intPriorityQueueExample);

  cout << "The size of intPriorityQueueExample is: " << intPriorityQueueExample.size() << "n";
  cout << "The top-most element of intPriorityQueueExample is: " << intPriorityQueueExample.top() << "n";

  cout << "intPriorityQueueExample after popping an element:";
  intPriorityQueueExample.pop();
  printPriorityQueue(intPriorityQueueExample);

  cout << "Is intPriorityQueueExample empty?: " << intPriorityQueueExample.empty() << "n";
  priority_queue  intPriorityQueueExample2;

  // Swapping intPriorityQueueExample with the empty intPriorityQueueExample2
  intPriorityQueueExample.swap(intPriorityQueueExample2);
  cout << "Is intPriorityQueueExample empty after swapping with intPriorityQueueExample2?: " << intPriorityQueueExample.empty() << "n";

  // Note that we can also have a min heap priority queue as shown below
  priority_queue < int, vector  , greater  > intPriorityQueueExample3;
  intPriorityQueueExample3.push(10);
  intPriorityQueueExample3.push(40);
  intPriorityQueueExample3.push(20);
  intPriorityQueueExample3.push(30);

  cout << "The priority queue intPriorityQueueExample3 contains (min heap):";
  printPriorityQueueMinHeap(intPriorityQueueExample3);

  return 0;
}

Output


The priority queue intPriorityQueueExample contains (max heap): 8 6 4 2
The size of intPriorityQueueExample is: 4
The top-most element of intPriorityQueueExample is: 8
intPriorityQueueExample after popping an element: 6 4 2
Is intPriorityQueueExample empty?: 0
Is intPriorityQueueExample empty after swapping with intPriorityQueueExample2?: 1
The priority queue intPriorityQueueExample3 contains (min heap): 10 20 30 40

Check out the learn page for more!

FAQs on C++ STL Container Fundamentals: priority_queue

Q1. Is there any STL container for a priority queue in C++?

Yes. The Standard Template Library or STL provides the container priority_queue as an implementation of the data structure priority queue in C++.

Q2. What is a priority_queue in C++ STL?

C++ STL priority_queue is a container adapter like a regular STL queue, with the queue elements having priorities associated with them. 

Q3. What functions are associated with priority_queue in C++ STL?

Top, push, pop, empty, size, swap, and emplace are some functions associated with priority_queue in C++ STL.

Q4. What problems are priority queues used to solve?

Priority queues are used to solve problems involving queues with elements having varying priorities like in maps (when the shortest path should have the highest priority), emergency queues, OS load balancing, interrupt handling, data compression, and traffic lights.

Q5. What kind of heap does C++ STL priority_queue maintain by default?

By default, priority queues maintain a max-heap. We need to specify if we want it to maintain a min-heap explicitly.

Ready to Nail Your Next Coding Interview?

Whether you’re a coding engineer gunning for a software developer or software engineer role, a tech lead, or you’re targeting management positions at top companies, IK offers courses specifically designed for your needs to help you with your technical interview preparation!

If you’re looking for guidance and help with getting started, sign up for our FREE webinar. As pioneers in the field of technical interview preparation, we have trained thousands of software engineers to crack the most challenging coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!

Sign up now!

‍

Last updated on: September 25, 2024
Register for our webinar

Uplevel your career with AI/ML/GenAI

Loading_icon
Loading...
1 Enter details
2 Select webinar slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Spring vs Spring Boot

Spring vs Spring Boot: Simplifying Java Application Development

Reinforcement Learning: Teaching Machines to Make Optimal Decisions

Reinforcement Learning: Teaching Machines to Make Optimal Decisions

Product Marketing vs Product Management

Product Marketing vs Product Management

Java Scanner reset()

The upper() Function in Python

Insertion Sort Algorithm

Ready to Enroll?

Get your enrollment process started by registering for a Pre-enrollment Webinar with one of our Founders.

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC