×

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

C++ Polymorphism

Polymorphism refers to the fact that something exists in several forms. Polymorphism, in simple terms, is the ability of a message to be presented in several formats. A real-life example...

4 minutes read.

strcat() vs strncat() in C++

In this tutorial, we will explore about strcat() and strncat() in the most usable language C++. We will also look at the difference between them. strcat() C++ is a computer language with...

4 minutes read.

C++ Friend function

A friend function has the right to access all private and protected members of a class although it is defined outside that class' scope. Syntax class className{     ......     friend retyrn_type function_Name(argument);     .......   }   return_type function_Name(argument){     ......   } C++ friend function Example #include <iostream>   using namespace std;   class Length   {       private:           int meter;       public:           Length(): meter(5) { }           friend int addMethod(Length); //friend function declaration   };   int addMethod(Length l) // friend function definition   {       l.meter += 10; //accessing private data from non-member function       return l.meter;   }   int main()   {       Length L;       int totallength;       totallength=addMethod(L);       cout<<"Length: "<< totallength;       return 0;   } Output: Length: 15   C++ friend function...

1 minute read.

C++ Type Casting

The type casting of variables in the C++ programming language will be covered in this section. The term "type casting" describes how software converts one data type to another. There...

9 minutes read.

Free vs delete() in C++

Free vs delete() in C++ In this section, we will learn about the free() function and also create a C ++ program of the delete operator. What is free() Function in C++? In...

4 minutes read.

Division in C++

C++ Division Arithmetic Operation In C++ the arithmetic operator / is used for division. This operator takes two operands and returns the result of dividing the left operand by the right...

3 minutes read.

Scope Resolution Operator in C++

The scope resolution operator and its different usage in the C++ programming language will be discussed in this section. The scope resolution operator is used to refer to an out-of-scope...

6 minutes read.

Programs to Print Pyramid Patterns in C++

We will explore how to use code to print a variety of patterns utilizing stars (*), numbers (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,.…)  and alphabets...

7 minutes read.

Multilevel Inheritance

C++ Multilevel Inheritance Multilevel inheritance is such an inheritance in which a derived class is created from another derived class. C++ Multilevel Inheritance Example In this example, a base class Student is inherited in...

2 minutes read.

Diamond Pattern using While-loop in C++

What is while Loop? A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the...

5 minutes read.

Array of Vectors in C++ STL

Prerequisites: C++ STL Arrays and C++ STL Vector. A group of items kept in consecutive memory region is known as an array. It is to group similar objects of the same...

4 minutes read.

Stringstream in C++ and its applications

In this tutorial, we will explore what the stringstream in C++ is. We will also learn its application. What is stringstream? With the aid of a stringstream, user can read from a...

2 minutes read.

Top 5 IDEs for C++ That You Should Try Once

In the past decades, creating an application or interface from the very basic idea, the developer has to struggle a lot for it. Because an application is a combination of...

3 minutes read.

Structured Binding in C++

Structured binding is the new feature of C++ 17. It is used to bind the specified name with an element of the initializer. Structure binding is used to declare multiple...

3 minutes read.

C++ Call by Reference

Call by Reference is a C++ method for passing arguments to a function that enables us to pass the actual memory address of the parameter rather than a copy of...

4 minutes read.

C++ Pointer

Pointer is a derived data type that stores the address of a variable. A pointer is used for memory management and dynamic memory allocation. Pointer works on the address of data rather than...

2 minutes read.

C++ Date and Time

The date and time formats in C++ will be covered in this article. Because C++ lacks a proper date and time format, we must rely on the c language. The...

7 minutes read.

Differences Between C Structures and C++ Structures

The below table clearly describes the differences between C and C++ programming languages Structures concepts where the core principle concepts like static members, data handling, pointers, access modifiers, the importance...

3 minutes read.

gmtime() function in C/C++

C++ language is used to make high-performance applications that can work efficiently. It is one of the world's most popular languages. It is an object-oriented and high-level programming language, which...

4 minutes read.

Destructor

Let’s discover the C++ destructor, virtual and pure virtual destructors, and when destructors are invoked and their rules in this lesson. Destructors : A member function that destroys an object is known as...

5 minutes read.