How to create a custom comparator to insert and sort elements by value in a map in C++? Generally in a map, elements are sorted by key. I want to soet by value.
Asked
Active
Viewed 256 times
-5
-
What have you tried to achieve your wanted result? – Geshode Jun 20 '18 at 01:48
-
4It is as contradictory as "dehydrated water". By definition, the thing being sorted by is the key or a part of the key. By definition, you can't sort by value. – Jun 20 '18 at 01:54
-
2if you sort by value, that value is the "key" – kmdreko Jun 20 '18 at 02:40
-
Keep in mind that keys are required to be unique, but values are not. – user1118321 Jun 20 '18 at 04:54
1 Answers
-1
This is not possible in C++ to sort map based on its values due to its internal implementation. Map sorts elements only based on its key.
But there is a way you can achieve what you want.(Both needs additional space though.)
1) If you only want all the values to be sorted & not needing their mapping. You can put all the keys in a vector and then sort the vector.
2) And suppose you want that mapping too. Then you can create a vector of pair<> and then define a comparator to sort based on second value of pair.
bool sortBySecond(const pair<int, int> &a, const pair<int, int> &b){
return (a.second < b.second);
}
Inside main:
vector<pair<int, int> > vect;
sort(vect.begin(), vect.end(), sortBySecond);
The above vector will have pair sorted on the basis of your values of map in ascending order.

Rohit Agrawal
- 51
- 7