![]() |
VOOZH | about |
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.
To achieve this, we can use the function from the header along with a 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.
sort(first, last, comp);
Here, first and last define the range of elements to sort, and comp is the comparator function or lambda expression.
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++.
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)