c++ - How can i get the top n keys of std::map based on their values? -


how can top n keys of std::map based on values? there way can list of example top 10 keys biggest value values?
suppose have map similar :

mymap["key1"]= 10; mymap["key2"]= 3; mymap["key3"]= 230; mymap["key4"]= 15; mymap["key5"]= 1; mymap["key6"]= 66; mymap["key7"]= 10;  

and want have list of top 10 keys has bigger value compared other. example top 4 our mymap

key3 key6 key4  key1 key10  

note:
values not unique, number of occurrences of each key. , want list of occurred keys

note 2:
if map not candidate , want suggest anything, please according c++11 ,i cant use boost @ time.

note3:
in case of using std::unordered_multimap<int,wstring> have other choices?

the order of map based on key , not values , cannot reordered necessary iterate on map , maintain list of top ten encountered or commented potatoswatter use partial_sort_copy() extract top n values you:

std::vector<std::pair<std::string, int>> top_four(4); std::partial_sort_copy(mymap.begin(),                        mymap.end(),                        top_four.begin(),                        top_four.end(),                        [](std::pair<const std::string, int> const& l,                           std::pair<const std::string, int> const& r)                        {                            return l.second > r.second;                        }); 

see online demo.

choosing different type of container may more appropriate, boost::multi_index worth investigating, which:

... enables construction of containers maintaining 1 or more indices different sorting , access semantics.


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -