I am trying to make a character frequency map that, on every insert, puts the character with the highest frequency at the start of the map.
So, it would be like a std::map<char, int> and I would iterate the string and do map[string[i]]++ to increment the frequency count for each character. On every increment, the map would sort itself like a priority queue and put the key-value pair with the highest frequency at the beginning of the map so I can retrieve with map.begin().
I tried to make a custom comparator for std::map, but some incomprehensible error messages came out.
#include <map>
#include <string>
using namespace std;
struct cmpByValue
{
bool operator()(const pair<char, int>& p1, const pair<char, int>& p2)
{
return p1.second > p2.second;
}
};
int main(void)
{
map<char, int, cmpByValue> freq_map;
string s = "ASDASDASD";
for (int i=0; i<s.size(); ++i)
{
freq_map[s[i]]++;
}
return 0;
}
I know that std::map automatically sorts the elements based on the keys, but since I want it to sort by frequency, it would have to sort by value instead of key.
Is this possible?
What you are attempting to do with
std::map(or any associative container, for that matter) is simply not feasible, as it sorts its elements on keys only, not on their mapped values. You can't makestd::mapmove its elements around when the values change, only when the keys change.So, you will have to sort your
std::mapelements after you are done calculating all of the frequency values, eg:Online Demo
That being said - since you stated:
Then you could simply use
std::priority_queueinstead, eg:Online Demo