Priority Queue of Vectors in C++ STL with Examples

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

10 20 35 40 
30 25 10 50 
30 25 10 50

GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.