Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
priority_queue::push() and priority_queue::pop() in C++ STL
Next article icon

Priority Queue in C++ STL

Last Updated : 19 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, priority queue is a type of queue in which there is some priority assigned to the elements. According to this priority, elements are removed from the queue. By default, the value of the element being inserted is considered as priority. Higher its value, higher its priority. But this can be changed to any desired priority scheme as per requirement.

Example:

C++
#include <iostream> #include <queue> using namespace std;  int main() {          // Creating a priority queue of integers     priority_queue<int> pq;     pq.push(9);     pq.push(10);     pq.push(6);          cout << pq.top() << " ";     return 0; } 

Output
10 

Explanation: In the above program, we created a priority queue of integers that contains the elements 9, 10 and 6. The top element, which is the largest value in the queue, is then printed.

Syntax

Priority queue is defined as std::priority_queue inside <queue> header file.

priority_queue<T, c, comp> pq;

where,

  • T: Type of the priority queue
  • pq: Name assigned to the priority queue.
  • c: Underlying container. Uses vector as default.
  • comp: It is a binary predicate function that tells priority queue how to compare two elements. It is used to set the custom priority parameter and scheme. It is optional and if not provided, maximum value gets maximum priority.

Internal Working

Priority queue container provides the built-in implementation of a binary heap data structure. There can be two types of heaps,

  • Max-heap in which the priority is given to the largest element. (Default)
  • Min-heap in which the priority is given to the smallest element.

Priority queue is a container adaptor generally built over vector container. We can implement both of these heaps in priority queue.

Declaration and Initialization

Priority queue can be declared and initialized in multiple ways as shown in the below example:

C++
#include <bits/stdc++.h> using namespace std;  void print(priority_queue<int> pq) {     while (!pq.empty()) {         cout << pq.top() << " ";         pq.pop();     } }  int main() {          // Create empty priority queue     priority_queue<int> pq1;          // Insert values     pq1.push(9);     pq1.push(8);     pq1.push(6);     print(pq1);     cout << endl;          // Creating priority queue from other container     vector<int> v = {9, 8, 6, 10, 4, 2};     priority_queue<int> pq2(v.begin(), v.end());     print(pq2);          return 0; } 

Output
9 8 6  10 9 8 6 4 2 

Explanation: In the above program, two priority queues are initialized in the following ways:

  • Statement priority_queue<int> pq1 creates an empty priority queue of integers. Elements are later inserted.
  • Statement priority_queue<int> pq2(v.begin(), v.end()) creates a priority queue and initializes it with the same elements as those in the vector v. We can use any other container too.

Both priority queues will have the largest element at the top.

Basic Operations

Here are the basic operations that can be performed on a priority queue:

1. Inserting Elements

Elements can be inserted in the priority queue using push() method. After insertion, priority queue reorganize itself in such a way that the highest priority element is always at the top.

Example:

C++
#include <bits/stdc++.h> using namespace std;  int main() {     priority_queue<int> pq;          // Inserting elements     pq.push(9);     pq.push(8);     pq.push(6);          cout << pq.top();     return 0; } 

Output
9

Explanation: In the above program, elements 9, 8 and 6 are inserted into the priority queue using push() method one by one. After insertion, the largest element 9 is at the top.

2. Accessing Elements

Only the top element of the priority queue can be accessed using top() method. It is the element with the highest priority in priority queue.

Example:

C++
#include <bits/stdc++.h> using namespace std;  int main() {     priority_queue<int> pq;     pq.push(9);     pq.push(8);     pq.push(6);          // Accessing top element     cout << pq.top();     return 0; } 

Output
9

3. Deleting Elements

In priority queue, deletion can only be done from the top of the priority queue using pop()method. It means that we can only remove the element with highest priority in one move. After deletion, the priority queue rearranges itself such that the next greatest priority element becomes the top element.

C++
#include <bits/stdc++.h> using namespace std;  int main() {     priority_queue<int> pq;     pq.push(9);     pq.push(8);     pq.push(6);          // Delete top element     pq.pop();     cout << pq.top();          return 0; } 

Output
8

Explanation: In this example, we deleted the top element using pop() method, which is 9. This shifts the next greatest element 8 to the top.

4. Pseudo Traversal

In priority queue, we can only access top element of the priority queue, so we cannot directly traverse it. However, we can create a copy of the priority queue, access and delete the top element and repeat this process until the copied priority queue is empty. In this way, we can effectively traverse all the elements of the priority queue.

Example:

C++
#include <bits/stdc++.h> using namespace std;  int main() {     priority_queue<int> pq;     pq.push(9);     pq.push(8);     pq.push(6);          // Create a copy     priority_queue<int> temp(pq);          // Traverse     while(!temp.empty()) {         cout << temp.top() << " ";         temp.pop();     }     return 0; } 

Output
9 8 6 

5. Changing Priority Queue Order

All the above operations are demonstrated on a priority queue implementing max heap. This can be changed by using a custom comparator in which you define the priority parameter and how to compare them.

If you only want to assign highest priority to the smallest element (min-heap), then inbuilt greater<type> functional object can be used.

Example:

C++
#include <bits/stdc++.h> using namespace std;  int main() {          // Creating priority queue     priority_queue<int, vector<int>,                     greater<int>> pq;     pq.push(9);     pq.push(8);     pq.push(6);          auto temp = pq;     while(!temp.empty()) {         cout << temp.top() << " ";         temp.pop();     }     return 0; } 

Output
6 8 9 

Explanation: In the above program, even though vector is default container, we still have to pass it because the comparator is third template argument. So, we have to pass all the arguments before it.

Time Complexity

The below table lists the time complexity of the above operations on priority queue:

OperationTime Complexity
Add elementO(log n)
Delete elementO(log n)
Find maximum element in max heap.O(1)

Find minimum element in min heap.

O(1)

Initialize priority queue from another container.

O(n)

Other Common Operations

The following are some more operations on priority queue that will help you become more familiarize with this container:

  • Find the Size of Priority Queue
  • Check if Priority Queue is Empty
  • Reverse Priority Queue
  • Create Priority Queue of Tuples
  • Create Queue with Custom Priority Criteria
  • Swap Priority Queue

Priority Queue vs Queue

Following is the primary differences between priority queue and queue in C++:

  • A queue follows the First in First Out (FIFO) principle, where the first element inserted is the first element to be removed.
  • A priority queue stores elements in order of priority, where the highest priority element is always at the top no matter when it is inserted.

All Member Functions

Following is the list of all member functions of std::priority_queue class in C++:

Function

Definition

empty()Returns whether the priority queue is empty.
size() Returns the size of the priority queue.
top()Returns top element of the priority queue
push() Adds the element into the priority queue.
pop()Deletes the top element of the priority queue.
swap()Used to swap the contents of two priority queues provided the queues must be of the same type, although sizes may differ.
emplace()Used to insert a new element into the priority queue container.

Next Article
priority_queue::push() and priority_queue::pop() in C++ STL

K

kartik
Improve
Article Tags :
  • C++
  • STL
  • cpp-containers-library
  • cpp-priority-queue
Practice Tags :
  • CPP
  • STL

Similar Reads

    Priority Queue in C++ STL
    In C++, priority queue is a type of queue in which there is some priority assigned to the elements. According to this priority, elements are removed from the queue. By default, the value of the element being inserted is considered as priority. Higher its value, higher its priority. But this can be c
    6 min read
    priority_queue::push() and priority_queue::pop() in C++ STL
    In C++, priority_queue::push() and priority_queue::pop() methods are used to insert and delete the element from the priority_queue container. They both are the member functions of std::priority_queue class defined inside <queue> header file. In this article, we will learn about priority_queue:
    2 min read
    priority_queue::top() in C++ STL
    Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue. In general, elements are arranged according to some priority. However in C++ STL, the top element is the greatest elem
    3 min read
    priority_queue::empty() and priority_queue::size() in C++ STL
    Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue. However, in C++ STL (by default) the largest element is at the top. We can also create a priority queue having the sma
    4 min read
    priority_queue emplace() in C++ STL
    Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue. However, in C++ STL (by default) the largest element is at the top. We can also create a priority queue having the sma
    4 min read
    priority_queue::swap() in C++ STL
    Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue. However, in C++ STL (by default) the largest element is at the top. We can also create a priority queue having the sma
    3 min read
    priority_queue value_type in C++ STL
    The priority_queue :: value_type method is a built-in function in C++ STL which represents the type of object stored as an element in a priority_queue. It acts as a synonym for the template parameter. Time complexity: O(1)Syntax: priority_queue::value_type variable_name It has no parameters and no r
    2 min read
    Priority Queue of Sets in C++ with Examples
    Priority Queues Priority queues are a type of container adapters, specifically designed such that the first element of the queue is the greatest of all elements in the queue and elements are in nonincreasing order (hence we can see that each element of the queue has a priority {fixed order}). Functi
    4 min read
    Priority queue of pairs in C++ with ordering by first and second element
    Priority Queue: Priority queue is the extension of the queue in which elements associated with priority and elements having higher priority is popped first. Priority queue can contain elements with various data types such as integer, pair of integers, custom data type. But one thing is common that t
    5 min read
    Multiple comparisons in a C++ priority queue?
    What is a Priority Queue? A Priority Queue is an abstract data type that is similar to a queue, and every element has some priority value associated with it. The priority of the elements in a priority queue determines the order in which elements are served (i.e., the order in which they are removed)
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences