![]() |
In C++, the pair container allows the users to store two different types of objects as a single unit. We can store the pairs in a list if we want to store multiple pairs in a single place. Lists are sequence containers that allow non-contiguous memory allocation. In this article, we will learn how to sort a list of pairs in different orders in our C++ program. For Example, Input: Sort List of Pairs in C++We can use the std::list::sort() function to sort the list but for a list of pairs, we will have to provide a custom comparator function (can be a lambda expression) to compare the elements of each pair with others.
C++ Program to Sort List of Pairs in Ascending OrderC++
Output
List Initially ( 300, 1 ) ( 200, 2 ) ( 100, 3 ) ( 400, 4 ) List After Sorting: ( 100, 3 ) ( 200, 2 ) ( 300, 1 ) ( 400, 4 ) In the above program, we have sorted the list according to the value of the first element of the pair. We can also sort the list based on the value of the second element.
C++ Program to Sort the List of Pairs According to the Second ElementC++
Output
List Initially ( 300, 3 ) ( 200, 2 ) ( 100, 1 ) ( 400, 4 ) List After Sorting: ( 400, 4 ) ( 300, 3 ) ( 200, 2 ) ( 100, 1 ) The above program sorts the list based on the value of the second element of the pair. It also sorts the list in the descending order. We can actually sort the list in any order we want by providing a comparator function of our choice.
|
Reffered: https://www.geeksforgeeks.org
C++ |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |