Javatpoint Logo
Javatpoint Logo

Priority queue of pairs in C++ with ordering by first and second element

Introduction

A basic data structure in computer science, priority queues enable quick access to the element with the highest (or lowest) priority. Priority queues in C++ can be expanded to handle pairs, providing a flexible method of sorting according to the first or second element of the pair. This post will explain how to build a custom comparator for ordering by the first or second element as we delve into the nuances of using priority queues of pairs in C++.

Understanding Priority Queues

A priority queue is a type of data structure that keeps track of a number of elements, each of which has a priority. It then makes it possible to quickly retrieve the element with the highest (or lowest) priority. Implementing a priority queue in C++ is made easier by the priority_queue template found in the <queue> header. A priority queue is a container that can continuously retrieve the element with the highest (or lowest) priority. The priority_queue container adapter in C++ makes use of a heap to manage elements so that the maximum (default) or minimum element can be retrieved in a constant amount of time.

Basic Usage of Priority Queues of Pairs

Prior to using a priority queue of pairs, the pair type must be defined. After that, the priority queue must be declared using the correct template parameters. As an illustration:

Output:

Priority queue of pairs in C++ with ordering by first and second element

Code Explanation

Header Inclusions

  • These lines contain the header files that are needed. It is used to use the priority_queue container and for input and output operations.

Namespace Declaration

  • This line lets you use standard C++ library elements without having to prefix them with std::.

Main Function

  • The program's entry point, from which execution starts.

Priority Queue Declaration

  • Creates a priority queue called pq to hold integer pairs. By default, the pairs are arranged according to the first element in descending order.

Pushing Pairs into the Priority Queue

  • The push method is used to push pairs of integers into the priority queue.

Elements Printing and Popping

  • For as long as the priority queue is not empty, this while loop will keep running. Within the circle:
  • The pair with the highest priority (the first element in descending order) is obtained using pq.top().
  • Cout prints the pair's first and second elements.
  • The element in the priority queue with the highest priority is removed by pq.pop().

Return Statement

  • Shows that the program was executed successfully.

Custom Comparator for Priority Queues

Defining custom comparators for the purpose of ordering elements in containers such as priority queues is one of the most potent features of C++. When we wish to order based on the second element or use custom logic, this becomes crucial for pairs. You can define a custom comparator to order pairs using custom logic or based on the second element. The comparator is a class or struct that provides the required comparison logic by overloading the() operator. One possible application of a custom comparator is to arrange pairs in ascending order according to the second element.

Output:

Priority queue of pairs in C++ with ordering by first and second element

Code Explanation

Definition of a Custom Comparator

  • The purpose of the ComparePairs struct is to act as a unique comparator for pairs.
  • To specify the comparison logic, it overrides the() operator.
  • Here, pairs (a.first and b.first) are compared according to their first elements.

Declaration of Priority Queue with Custom Comparator

  • The pair type (\pair<int, int>>), the underlying container (vector<pair<int, int>>), and the custom comparator (ComparePairs) are specified in the template parameters used to declare the priority_queue.
  • This modifies the priority queue's ordering behavior in accordance with the logic specified in the ComparePairs struct.

Pairs are added to the priority queue as follows

  • The push method pushes pairs into the priority queue.
  • The priority queue's order is unaffected by the insertion order since elements are automatically rearranged in accordance with the custom comparator.

Elements Printing and Popping

  • As long as there is no empty priority queue, the while loop keeps running.
  • Using the custom comparator, pq.top() retrieves the pair with the highest priority inside the loop.
  • Cout prints the pair's first and second elements.
  • The element in the priority queue with the highest priority is removed by pq.pop().

Statement of Return

  • Indicates that the program was executed successfully.

Ordering by Second Element

Adjust the custom comparator in accordance with the second element to determine the order of pairs:

Output:

Priority queue of pairs in C++ with ordering by first and second element

Code Explanation

Includes

  • <iostream>: Offers functions for both input and output.
  • <queue>: Contains the priority_queue container definition.
  • <vector>: Contains the vector container's definition.

Namespace

  • It is possible to use standard C++ entities without having to prefix them with std:: by using the namespace std; statement.

Custom Functor

  • An overloading () operator is present in the functor defined by the ComparePairsBySecond struct.
  • Pairs in the priority queue are compared using this functor. The second element of each pair is used for comparison, and that element will be ranked lower in the priority queue.

Priority Queue Declaration

  • vector<pair<int, int>>, priority_queue<pair<int, int>, ComparePairsBySecond> pq; Uses the custom comparison logic provided by the ComparePairsBySecond functor to declare a priority queue of integer pairs.

Pushing Elements into the Priority Queue

  • The following pairs are moved up to the priority queue: {3, 10}, {1, 5}, {2, 8}, and {4, 2}.

Processing and Printing

  • After that, the code goes into a while loop, which keeps running until the priority queue is empty.
  • Using cout, the pair with the highest second element in the priority queue is printed at the top of each iteration.
  • The top element in the priority queue is then deleted by calling the pop() function.

Output

  • The pairs of their second elements printed in descending order will be the program's output.

Advanced Techniques

Priority queues of pairs can be utilized in a variety of advanced scenarios, going beyond the fundamentals. Advanced methods may be used, depending on the use case. These include using pairs with different data types, modifying the comparison logic for complex scenarios, and building a min-heap rather than a max-heap. Let's investigate a few methods:

Ordering Logic Customization

To support intricate ordering criteria, the custom comparator's comparison logic can be further modified. For example, consider taking into account both the first and second elements when ordering pairs lexicographically. Lexicographical ordering is a popular use case in which pairs are arranged according to the first element and then the second element if they are equal. To do this, define a custom comparator that takes into account both elements.

Pairs are arranged lexicographically by this comparator, which bases its order on the first element if they are equal and the second element otherwise.

Using Pairs with Different Data Types

For the first and second elements, pairs can contain a variety of data types. An integer and a string pair could be in your priority queue, for instance. Different data types for both the first and second components can be contained in pairs. For instance, a pair could have a string and an integer in it. The comparison of heterogeneous types needs to be handled carefully by custom comparators.

In these situations, the custom comparator needs to handle the heterogeneous type comparison properly.

Building a Min-Heap

Priority_queue builds a max-heap by default. You can adjust the custom comparator if a min-heap is required.

A min-heap is generated by this comparator using the first element and, if required, the second element.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA