![]() |
In C++, a vector of pairs is a common data structure used to store pairs of values. Sometimes, when dealing with pairs we need to sort such vectors of pairs based on a specific element of the pair like sorting it based on the second element of each pair. In this article, we will learn how to sort a vector of pairs based on the second element of the pair in C++. Example: Input: In the above example, the vector my_vector contains pairs of integers. We want to sort the vector based on the second element of each pair, resulting in a vector sorted in ascending order of the second elements. Sorting a Vector of Pairs Based on the Second ElementTo achieve this, we can use the std::sort function from the <algorithm> header along with a custom comparator. The comparator will define how the pairs should be compared based on their second element. Approach:
Syntax to use std::sort with Custom Comparatorsort(first, last, comp); Here, first and last define the range of elements to sort, and comp is the comparator function or lambda expression. C++ Program to Sort a Vector of Pairs Based on the Second Element of the PairBelow is the implementation of the above approach illustrated to sort a vector of pairs based on the second element of the pair in C++.
Output Vector after sorting based on the second element: {3, 1} {2, 2} {5, 3} {1, 4} Time Complexity: O(nlogn), here n is the number of elements in the vector. |
Reffered: https://www.geeksforgeeks.org
C++ |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 18 |