Skip to content
Related Articles

Related Articles

Improve Article

Priority Queue of Vectors in C++ STL with Examples

  • Difficulty Level : Medium
  • Last Updated : 17 Mar, 2020

Priority Queue in STL 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 non increasing order(hence we can see that each element of the queue has a priority{fixed order})

Vector in STL Vector is same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators.

Priority Queue of Vectors in STL: Priority Queue of Vectors can be very efficient in designing complex data structures.

Syntax:

priority_queue<vector<datatype>> pq;

For example: Consider a simple problem where we have to print the maximum vector that is in the queue.






// C++ program to demonstrate
// use of priority queue for vectors
  
#include <bits/stdc++.h>
using namespace std;
  
priority_queue<vector<int> > pq;
  
// Prints maximum vector
void Print_Maximum_Vector(vector<int> Vec)
{
    for (int i = 0; i < Vec.size(); i++) {
        cout << Vec[i] << " ";
    }
    cout << endl;
    return;
}
  
// Driver code
int main()
{
    // Initializing some vectors
    vector<int> data_1{ 10, 20, 30, 40 };
    vector<int> data_2{ 10, 20, 35, 40 };
    vector<int> data_3{ 30, 25, 10, 50 };
    vector<int> data_4{ 20, 10, 30, 40 };
    vector<int> data_5{ 5, 10, 30, 40 };
  
    // Inserting vectors into priority queue
    pq.push(data_1);
    pq.push(data_2);
  
    // printing the maximum vector till now
    Print_Maximum_Vector(pq.top());
  
    // Inserting vectors into priority queue
    pq.push(data_3);
  
    // printing the maximum vector till now
    Print_Maximum_Vector(pq.top());
  
    // Inserting vectors into priority queue
    pq.push(data_4);
    pq.push(data_5);
  
    // printing the maximum vector till now
    Print_Maximum_Vector(pq.top());
  
    return 0;
}
Output:
10 20 35 40 
30 25 10 50 
30 25 10 50

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :