[英]Sort a map in c++
I have a map
with a number attached to an alphabet
. 我有一个
map
与连接到一些alphabet
。 The map
is sorted by default using first value but I want to sort it by frequency
ie second value and then print it. 默认情况下,
map
使用第一个值进行排序,但我想按frequency
即第二个值)对其进行排序,然后打印出来。 Please help me do that Edit:: There is nothing I can try here 请帮我做到这一点编辑::没有什么我可以在这里尝试
You can't sort map
directly according to its second value. 您不能直接根据
map
的第二个值对map
排序。 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. 首先,将
map
的数据保存为pair
的vector
,然后根据需要对向量进行排序。
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. 现在,
mapcopy
(它是一个向量)具有所需的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.