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:
vector<pair<int, int>> my_vector = {{1, 4}, {3, 1}, {5, 3}, {2, 2}};
Output:
vector<pair<int, int>> my_vector = {{3, 1}, {2, 2}, {5, 3}, {1, 4}}; //after sorting
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 Element
To 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:
- Use the sort function to sort the vector.
- Provide a lambda function or a separate function defined to compare pairs based on their second element using a.second < b.second. Pass it as the third argument to std::sort.
- The result is a vector sorted in ascending order of the second elements of the pairs.
Syntax to use std::sort with Custom Comparator
sort(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 Pair
Below is the implementation of the above approach illustrated to sort a vector of pairs based on the second element of the pair in C++.
// C++ Program to illustrate how to sort a vector of pairs
// based on the second element of the pair
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// Initialize the vector of pairs
vector<pair<int, int> > my_vector
= { { 1, 4 }, { 3, 1 }, { 5, 3 }, { 2, 2 } };
// Sort the vector based on the second element of the
// pair
sort(my_vector.begin(), my_vector.end(),
[](const pair<int, int>& a,
const pair<int, int>& b) {
return a.second < b.second;
});
// Output the sorted vector
cout << "Vector after sorting based on the second "
"element: ";
for (const auto& p : my_vector) {
cout << "{" << p.first << ", " << p.second << "} ";
}
cout << endl;
return 0;
}
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.
Auxiliary Space: O(1)