sorting a hash_map

Started by
7 comments, last by ToohrVyk 18 years, 1 month ago
hash_map seems so ugly... I have a hash_map of type <string, int>, and need to sort from highest to lowest by the int values... I'm using g++. What would be the easiest function to do that with? [Edited by - BTownTKD on April 23, 2009 9:31:53 AM]
Deep Blue Wave - Brian's Dev Blog.
Advertisement
You can't sort a hash_map, especially by value. You can copy the elements into a different container and sort it, though.
//pseudofor(Iterator i = myHashMap.begin(); i != myHashmap.end(); ++i)   myMap[i->second] = i->first;

CM
What function, then, would be the fastest for sorting a map<string, int> by the int values? Is there a quick, easy function in the <algorithm> library?
Deep Blue Wave - Brian's Dev Blog.
Quote:Original post by BTownTKD
What function, then, would be the fastest for sorting a map<string, int> by the int values? Is there a quick, easy function in the <algorithm> library?


You could use std::transform to transform your source map into a map<int, string>, given a simple adapting functor.

Stephen M. Webb
Professional Free Software Developer

Quote:Original post by Bregma
Quote:Original post by BTownTKD
What function, then, would be the fastest for sorting a map<string, int> by the int values? Is there a quick, easy function in the <algorithm> library?


You could use std::transform to transform your source map into a map<int, string>, given a simple adapting functor.


He would probably need a multi_map in that case.

Here's what I did... maybe someone can tell me if this is good thinking or not.


STL's sort requires random-access iterators -- like those found in a vector -- so I copied all the data in my hash_map over to a vector< pair< string, int> >, and created a custom function that compares two pair<string, int>s, and returns true if the first one is less than the second one...

I then called sort(tempVector.begin(), tempVector.end(), compare);

Note: compare is my function that compares 2 pair<string, int>s.

Is this a rediculous solution, or does it look pretty solid?
Deep Blue Wave - Brian's Dev Blog.
It is solid, but:

1° vector has a "sort" member function not.
2° as bregma suggested, it would be faster and more intuitive to create a multi_map<int,string> from your map.

[Edited by - ToohrVyk on March 13, 2006 3:17:49 PM]
Quote:Original post by ToohrVyk
1° vector has a "sort" member function


No it doesn't.

Oops.

This topic is closed to new replies.

Advertisement