×

Priority Queue in C++

Priority Queue in C++

Introduction:

We have already come across Queues by concluding that they are linear data structures that follow FIFO (First-In-First-Out) approach. We had also discussed the syntax of queues and the operations associated with them. Let us now talk about the sub-section of queue i.e. Priority Queue.

Definition:

As the name suggests, priority queues are the abstract data types similar to queues where the element has some additional priority associated with it. The element with higher priority in the queue is preferred than the element with lower priority.

A priority queue is associated with the following properties-

There is priority associated with every element.

A higher priority element is dequeued before the lower priority element.

If two elements have the same priority then the priority is given to the element occurring first in the order.

Also, there are various operations associated with priority queues. They are:

  1. insert(item, priority) : This is done to insert the element in the end of array in O(1) complexity.
  • getHighestPriority(): This is done by linear searching in the array having element of the higher priority. This usually takes O(n) complexity.
  • deleteHighestPriority(): This is done by pushing elements one subsequent position back by liner traversing over the array to search the item.

Let us now understand priority queues through the help of syntax and coding examples.

Syntax:

 template<
     class T,
     class Container = std::vector<T>,
     class Compare = std::less<typename Container::value_type>
 > class priority_queue; 

Here,

Template parameters are:

  1. Container: It stores the elements in sequential order. It has additional semantics like:
  2. front()
  3. push_back()
  4. pop_back()

Compare: It is used to compare the ordering in terms of strong and weak. The parameter of compare is defined as true if the first argument appears before the second argument in weak ordering.

Member TypesDefinition
container_type  Container
     Value_type  Value inside the container
      Size_type  Size nature of the container
reference  Container elements reference
Constant referenceConstant referencing elements
   Member Functions       Definition
Constuctor()Constructs the priority queue
Destructor()Removes the priority queue
Operator(=)Assigns values in the queue

These are basic member types and functional definitions associated with the syntax of Priority queues.

Lets us now look at coding example to understand the priority queues in a better sense.

 #include<bits/stdc++.h>
 using namespace std; 
 int main() 
 { 
  priority_queue<int> Q;  
  Q.push(100);
  Q.push(200);
  Q.push(300);
  cout<<"Number of elements available in 'Q' :"<<Q.size()<<endl; 
  while(!Q.empty()) 
  { 
      std::cout << Q.top() << std::endl;  
      Q.pop(); 
  } 
  return 0; 
 }  

Output:

Priority Queue in CPP

Explanation:

In the above code, we have created a single priority queue and the container contains 3 values 100,200, and 300 respectively. We could have also taken the value as inputs from the user. The next task is looping over the elements present in the queue and the queue which appears first will be printed first provided the loop iterates through the container until is not empty.

Note: We can also simply or define more priority queues depending upon the requirement. The approach will be as similar as shown in the above example.

Let us see how it is done in the coding example given below:

#include<bits/stdc++.h>
 using namespace std; 
 int main() 
 { 
 priority_queue<int> P;  
    priority_queue<int>Q;   
    P.push(23); 
    P.push(25);
    P.push(31);
    P.push(43);
    Q.push(51);  
    Q.push(64);
    Q.push(76);
    Q.push(85); 
    P.swap(Q); 
    std::cout << "P has following elements: " <<endl; 
    while(!P.empty()) 
    { 
       cout << P.top() <<endl; 
        P.pop(); 
    } 
    cout << "Q has following elements:" <<endl; 
     while(!Q.empty()) 
  { 
       cout << Q.top() <<endl; 
        Q.pop(); 
    } 
     return 0; 
 }   

Output:

Priority Queue in CPP

Explanation:

In the above code, we have defined two priority queues P and Q to show how the priority concept works. We have defined two template priority queues P and Q having different integer arguments.

The operations push(), pop(), and swap() are well-discussed functions in the previous sections where the top is checked and popped out to facilitate the entry of the next element in the priority queue.

The logic is to iterate over both the priority queues P and Q and get the values assigned to them on a priority basis. We can visualize that the elements in P and Q are constantly being swapped if the values after comparing are found greater or small. If the greater element is found in any of the P or Q queues then it is swapped and printed on the console in ascending order.

Advantages of Priority Queues:

The advantages are listed below:

  1. Priority queues are very easy to implement.
  • Processes with different priorities can be easily handled using priority queues.
  • Applications constituting different requirements in which highest or lowest elements may be needed, priority queues play a crucial role there.

Related Topics

Top 14 Best Free C++ IDE (Editor & Compiler) for Windows in 2024

Bjarne Stroustrup created the all-purpose object-oriented programming language C++. To develop C++ programs, there are various Integrated Development Environments (IDE) that offer prewritten code templates. These programs automatically modify the...

6 minutes read.

Print Table Using For-loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

3 minutes read.

Armstrong Number using Do-While Loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

4 minutes read.

Star pattern in C++ using For Loops

Star patterns are one of the most extensively utilized patterns in any programming language since they help to increase logical thinking and flow control understanding.In the C++ programming language, you...

3 minutes read.

How to create a stack in C++

A stack is a data structure, which is of linear type. A specific order has to be followed while inserting and deleting the elements from the stack. Generally, stack follows...

5 minutes read.

Snake Code in C++

Snake is a popular game that can be played on almost any device and runs on any operating system. In this game, snakes can move in any direction, including left,...

4 minutes read.

Constructor Vs Destructor in C++

C++ Constructor A function Object () { [native code] } is a member function that shares the same name as the class. It is called automatically whenever a class object is...

3 minutes read.

Array program in C++

What is an Array? An array is a set of identically typed elements that are organized into contiguous memory locations and each element can be independently accessed using an index. We can...

16 minutes read.

Message Passing in C++

The act of sending and receiving information by an object is referred to as communication, and all communication between objects that takes place via message is known as message passing....

1 minute read.

Virtual base class in C++

Consider in a C++ program, there are 4 classes named class A, class B, class C, and class D. If class B and class c inherit properties from class A....

3 minutes read.

Priority Queue in C++

Priority Queue in C++ Introduction: We have already come across Queues by concluding that they are linear data structures that follow FIFO (First-In-First-Out) approach. We had also discussed the syntax of queues...

4 minutes read.

C++ References

C++ References An alias is a reference variable that is another name for a variable already in existence. If a relation is initialized with a variable, it is possible to use...

3 minutes read.

C++ Recursion Function

A programming method called recursion that uses a function to call itself to address lesser problems. The Fibonacci sequence, factorial computation, and tree traversal are just a few of the...

4 minutes read.

Parameterize Constructor

C++ Parameterized Constructor A constructor having parameters is known as parameterize constructor. Parameterize constructor is used to assign different values. Syntax: className(data-type argument){   // Constructor definition   }   className(data-type argument, data-type argument){   // Constructor definition   } A parameterized constructor can be passed values to constructor function in two ways: 1)...

1 minute read.

How to find the length of the vector in C++

Like dynamic arrays, vectors can automatically adjust their size when an element is added or removed, and the container manages its storage. Because vector items are stored in contiguous storage, iterators...

3 minutes read.

C++ Math Functions

C++ Math Functions: Like other programming languages, C++ offers plenty of mathematical functions needed for various purposes. These functions are defined mainly in the math library in C++. Let us...

4 minutes read.

How to initialize a dynamic array in C++

Regular arrays or static arrays have a predetermined size or fixed size. Change in the size of regular arrays is not possible. The memory size for static arrays determines at compile...

4 minutes read.

sort() function in C++

This tutorial covers the various built-in sort functions found in the C++ algorithm’s library.  What Does C++ Sort Mean? The concept of sorting in C++ entails rearranging an array's elements in a...

3 minutes read.

C++ Void Pointer

A void pointer is a general purpose pointer that can have an address of any data type but is not related to any data type. Void Pointer Syntax: void *ptr;  We can't...

2 minutes read.

Palindrome Using While Loop in C++

A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++ also allows...

6 minutes read.