Sort Vector of Pairs in Ascending Order in C++
Last Updated :
17 Dec, 2024
Sorting a vector of pairs in ascending order means arranging the elements in such a way that first pair is lesser than second pair, second pair is lesser than third pair and so on.
The easiest way to sort the vector of pairs in ascending order is to use std::sort() function. The below code example illustrates this method:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<pair<int, char>> v = {{5, 'a'},
{1, 'c'}, {2, 'b'}};
// Sort above vector v
sort(v.begin(), v.end());
for (auto i : v)
cout << i.first << ": " << i.second
<< endl;
return 0;
}
Explanation: By default, sort() function sorts the vector of pairs in the ascending order of the first member of pairs. If the first members are equal, then it compares the second members.
There are also other methods available in C++ to sort the vector of pairs in ascending order. Let's look at each of them one by one.
Using sort() with Custom Comparison
To change the way of comparison, such as sorting on the basis of the second member of pairs, a custom comparator function that redefines the rules for comparing two pairs is used with sort().
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<pair<int, char>> v = {{5, 'a'},
{1, 'c'}, {2, 'b'}};
// Comparator that compares two pairs'
// second members
auto comp = [](pair<int, int> a, pair
<int,int> b) {
return a.second < b.second;
};
// Sort the vector of pairs
sort(v.begin(), v.end(), comp);
for (auto i : v)
cout << i.first << ": " << i.second
<< endl;
return 0;
}
Explanation: The comp lambda expression compares the second member of two pairs a and b and return true if the a.second is smaller than b.second. This function is passed to sort() as a parameter.
Using stable_sort()
The std::stable_sort() function is another sorting function available in C++ that can be used to sort the vector of pairs in ascending order just like sort() function.
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<pair<int, char>> v = {{5, 'a'},
{1, 'c'}, {2, 'b'}};
// Sort the vector of pairs
stable_sort(v.begin(), v.end());
for (auto i : v)
cout << i.first << ": " << i.second << endl;
return 0;
}
The stable_sort() function maintains the relative order of elements with equal keys which can be useful when you want to preserve the original order for equal elements.
Using Multiset
Elements in multiset container are stored in ascending order by default. So, we can create a std::multiset of pairs from the vector of pairs and then copy all the elements back to the vector to get it sorted.
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<pair<int, char>> v = {{5, 'a'},
{1, 'c'}, {2, 'b'}};
// Create the multiset with vector
multiset<pair<int, char>> ms(v.begin(),
v.end());
// Copy all elements of multiset
// back to vector
v.clear();
copy(ms.begin(), ms.end(), back_inserter(v));
for (auto i : v)
cout << i.first << ": " << i.second
<< endl;
return 0;
}
This method is not generally used as the above methods already work for almost every scenario. It is just mentioned here for informational purpose.
Similar Reads
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to Sorting Techniques â Data Structure and Algorithm Tutorials Sorting refers to rearrangement of a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure. Why Sorting Algorithms are ImportantThe sorting algorithm is important in Com
3 min read
Most Common Sorting Algorithms
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Heap Sort - Data Structures and Algorithms Tutorials Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use
14 min read
Counting Sort - Data Structures and Algorithms Tutorials Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that info
9 min read