![]() |
In C++, maps are associative containers that allow the users to store the data in the form of key-value pairs in some defined order. The maps are sorted in increasing order by default on the basis of the keys. In this article, we will learn how we can sort the Map by its second parameter i.e. values in C++. Example: Input: Sort a Map by Its Second Parameter in C++In C++, maps are implemented in red-black trees in which we consider the keys as the parameter for sorting. Due to this implementation, we can not sort the map based on its values. But we can create a vector of pairs and then sort this vector of pairs by its .second value using the std::sort() function. C++ Program to Sort a Map by its Second ParameterC++
Output
Map before soring: 10: 2 20: 1 30: 4 40: 3 Map after soring: 20: 1 10: 2 40: 3 30: 4 Time Complexity: O(N * logN) where N is the total number of elements in the map. |
Reffered: https://www.geeksforgeeks.org
C++ |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |