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
  • DSA
  • Data Structures
  • Array
  • String
  • Linked List
  • Stack
  • Queue
  • Tree
  • Binary Tree
  • Binary Search Tree
  • Heap
  • Hashing
  • Graph
  • Trie
  • Segment Tree
  • Disjoint Set Union
  • Fenwick Tree
  • AVL Tree
  • Red-Black Tree
  • Advanced Data Structures
Open In App

Multiple comparisons in a C++ priority queue?

Last Updated : 11 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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). If in any case, the elements have the same priority, they are served as per their ordering in the queue.

To learn more about priority queue, refer to the article on "Introduction to Priority Queue".

What is priority_queue STL in C++?

A 'priority_queue' is a container adaptor that provides us with a constant time lookup of the largest element at the expense of logarithmic insertion and extraction. We can use a user-provided compare function to change the order e.g. using std::greater<T> would cause the smallest element to appear at the top.

When we are using the priority queue we are basically using a heap in some random access container, which has the benefit of not being able to accidentally invalidate the given heap.

Priority Queue with a Custom Comparator 

Custom comparators are static functions that are used to define the parameter on which the given container is going to be sorted. It determines the way in which the given container is going to be sorted. 

If we use a '>' symbol then we are trying to sort in the ascending order else we are trying to sort in the descending order as '>' will return true when a > b (a is greater than b) else it will return false. So a swap will take place if the comparator is going to return false else no swap is going to take place. 

Let's see a program and further understand how this concept is going to be applied.

C++
#include <bits/stdc++.h> using namespace std;  // This template is used to print // the given heap again and again // irrespective of the given data type  template <class T> void printQueue(T& q) {     while (q.empty() == false) {         cout << q.top() << " ";         q.pop();     }     cout << endl; }  // Here we are using a basic priority queue // and sorting the queue in ascending order  void samplepriorityqueue() {     priority_queue<int, vector<int>, greater<int> > pq;     for (int i = 0; i < 10; i++) {         pq.push(i);     }     printQueue(pq); }  // Here we are using the lambda comparator function // to sort given priority queue in descending order void samplepriorityqueue1() {     auto compare = [](int left, int right) {         return left < right;     };     priority_queue<int, vector<int>, decltype(compare)> pq(         compare);     for (int i = 0; i < 10; i++) {         pq.push(i);     }     printQueue(pq); }  // Here we are using a comparator function // to sort the given priority queue. // This comparator function can be extended // to included several other features  struct mycmp {     bool operator()(int a, int b)     {         return a > b;     } };  void samplepriorityqueue2() {     priority_queue<int, vector<int>, mycmp> pq;     for (int i = 0; i < 10; i++) {         pq.push(i);     }     printQueue(pq); }  // Driver code int main() {     samplepriorityqueue();     samplepriorityqueue1();     samplepriorityqueue2();     return 0; } 

Output
0 1 2 3 4 5 6 7 8 9  9 8 7 6 5 4 3 2 1 0  0 1 2 3 4 5 6 7 8 9 

Here we see how the comparator is used to compare the defined datatypes and sort the data according to the comparator that we have given.

Multiple Comparisons in a C++ Priority Queue

Next, we are going to make multiple comparisons using the priority queue on a user-defined data type and then we are going to sort the data that has been given to us.

We can build a comparator function that compares more than one parameter and sort the data structure based on the conditions provided in the comparator. Below is an implementation of multiple comparisons in C++ priority queue.

C++
#include <bits/stdc++.h> using namespace std;  // Structure of a user defined data structure struct jobs { public:     int priority;     int processing;     int arrivaltime;     int proccessing_time;     string job;     jobs(int priority1, int processing1, int arrivaltime1,          int proccessing_time1, string s1)     {         this->priority = priority1;         this->processing = processing1;         this->arrivaltime = arrivaltime1;         this->proccessing_time = proccessing_time1;         this->job = s1;     } };  // Here we are sorting based on the processing time // if the priority is same and we are sorting // in descending order if the priority is same. // Else we are sorting in ascending order // on the priority of the tasks given to us struct compare {     bool operator()(jobs a, jobs b)     {         if (a.priority == b.priority) {             return a.processing < b.processing;         }         return a.priority > b.priority;     } };  // Driver code int main() {     priority_queue<jobs, vector<jobs>, compare> pq;     for (int i = 0; i < 10; i++) {         jobs a(rand() % 11, i + 1, rand() % 3 + i,                rand() % 5 + 3, "somejob" + to_string(i));         pq.push(a);     }      while (pq.empty() == false) {         jobs b = pq.top();         pq.pop();         cout << b.priority << " " << b.processing << " "              << b.arrivaltime << " " << b.proccessing_time              << " " << b.job << endl;     }     return 0; } 

Output
0 9 10 5 somejob8 0 8 7 6 somejob7 3 3 2 4 somejob2 4 2 3 3 somejob1 6 1 1 6 somejob0 7 5 5 3 somejob4 7 4 5 4 somejob3 10 10 10 6 somejob9 10 7 7 5 somejob6 10 6 5 4 somejob5

B

bornlegion
Improve
Article Tags :
  • Data Structures
  • C++
  • DSA
  • cpp-priority-queue
Practice Tags :
  • CPP
  • Data Structures

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