2011-03-19 48 views
2

可能重复的前10个值:
Sorting a std::map by value before output & destroy得到一个地图C++

map<string, int> Hosts; 

其中包含主机和主机被访问的次数进行量。

如何获得该地图的顶部X值?

+0

我发现,在我张贴它后,我正在尝试它的过程。 – Steven 2011-03-19 05:48:10

+0

经过一些修改(改变为只去map.size())它完美。请人们投票删除? – Steven 2011-03-19 05:50:44

+0

如果主题保持不变,则不存在问题。也许,它会帮助其他人,因为它会出现在搜索结果中! – Nawaz 2011-03-19 05:55:28

回答

1

我觉得如果你使用std::vector<std::pair<std::string, int>和使用std::sort提供自己compare函数(或仿函数),会更容易解决这个问题。您也可以使用std::map,按键排序元素。我认为你不需要容器按键(string),但按值(int)。

编辑:我只是注意到,即使是可能的重复也是如我所说的那样。它采用std::vector,所以你也用这个为:

std::vector<std::pair<std::string, int> Hosts; //Use this instead of map!