I can sort an unordered map by value in descending order using this answer.
However, using a set for the same job fails:
#include <set>
#include <functional>
#include <iostream>
using namespace std;
typedef pair<string, int> Pair;
typedef function<bool(Pair, Pair)> Comparator;
Comparator DescendingSortComparator = [](Pair pair1, Pair pair2) {
return pair1.second > pair2.second;
};
void SortHashTableByValueDescending(unordered_map<string, int> hashTable) {
set<Pair, Comparator> orderedSet(hashTable.begin(), hashTable.end(), DescendingSortComparator);
for (auto element : orderedSet)
cout << element.first << ": " << element.second << endl;
}
Running with the following test:
void Test_SortMap()
{
unordered_map<string, int> CountTable;
CountTable["word"] = 1;
CountTable["spark"] = 15;
CountTable["the"] = 2;
CountTable["mail"] = 3;
CountTable["info"] = 3;
CountTable["sandwich"] = 15;
SortHashTableByValueDescending(CountTable);
}
yiels the following output:
spark: 15
info: 3
the: 2
word: 1
Can anyone please tell me why set (probably) overwrites pairs with same value? The keys for such pairs are distinct anyways.