2

Possible Duplicate:
Sorting a std::map by value before output & destroy

map<string, int> Hosts;

Which contain a host and the amount of times that host was accessed.

How can I get the top X values of that map?

Community
  • 1
  • 1
Steven
  • 1,061
  • 2
  • 10
  • 14
  • I found that after I posted it sadly, I'm in the process of trying it. – Steven Mar 19 '11 at 05:48
  • After some modification (changing the for to only go to map.size()) it works perfect. Could people please vote to delete? – Steven Mar 19 '11 at 05:50
  • It's not a problem if the topic stays. Maybe, it'll help others as it'll come in search results! – Nawaz Mar 19 '11 at 05:55
  • if you didn't found it right away, it means that one more pointer to the original subject is worth keeping around. So we'll just close it as duplicate, so that people are redirected :) – Matthieu M. Mar 19 '11 at 11:20

2 Answers2

1

I think if you use std::vector<std::pair<std::string, int> and use std::sort providing your own compare function (or functor), that would solve this problem more easily. Also you use std::map which sorts the elements by their key. I think you don't need container which sorts by key (string), but by value (int).

EDIT: I just noticed that even the possible duplicate does the same thing as I said. It uses std::vector, so you also use this as:

std::vector<std::pair<std::string, int> Hosts; //Use this instead of map!
Nawaz
  • 353,942
  • 115
  • 666
  • 851
0

See comments for answer. Sorting a std::map by value before output & destroy

After some modification (changing the for to only go to map.size()) it works perfect. Could people please vote to delete?

Community
  • 1
  • 1
Steven
  • 1,061
  • 2
  • 10
  • 14