Reputation: 67
I have a map
with a number attached to an alphabet
. The map
is sorted by default using first value but I want to sort it by frequency
i.e second value and then print it. Please help me do that
Edit:: There is nothing I can try here
Upvotes: 0
Views: 172
Reputation: 1583
You can't sort map
directly according to its second value. But, it can be done manually. First, save the data of the map
into a vector
of pair
, and then sort the vector according to your need.
But anyways here is a little code snippet to perform the above explained operation:
template <typename T1, typename T2> struct less_second {
typedef pair<T1, T2> type;
bool operator ()(type const& a, type const& b) const {
return a.second < b.second;
}
};
map<key_t, value_t> mymap; /* It is map you want to sort according to the second argument*/
/* ...
...
... */
vector<pair<key_t, value_t> > mapcopy(mymap.begin(), mymap.end());
sort(mapcopy.begin(), mapcopy.end(), less_second<key_t, value_t>());
Now, mapcopy
(it is a vector) has your desired output.
Upvotes: 3