I would like to see an hash_map example in C ++

I do not know how to use the hash function in C ++, but I know that we can use hash_map . Does g ++ support this simply by including #include <hash_map> ? What is a simple example using hash_map ?

+43
c ++ hashmap
Feb 01 '10 at 20:46
source share
5 answers

There is no hash map in the current C ++ standard, but the following C ++ 0x standard does, and they are already supported by g ++ in the form of "unordered maps":

 #include <unordered_map> #include <iostream> #include <string> using namespace std; int main() { unordered_map <string, int> m; m["foo"] = 42; cout << m["foo"] << endl; } 

To get this compiler, you need to tell g ++ that you are using C ++ 0x:

 g++ -std=c++0x main.cpp 

These maps work almost the same as std :: map, except that instead of providing a custom operator<() for your own types, you need to provide a custom hash function - for types such as integers and strings, the corresponding functions.

+50
Feb 01 '10 at 20:50
source share

#include <tr1/unordered_map> will provide you with the following standard C ++ unique hash container . Using:

 std::tr1::unordered_map<std::string,int> my_map; my_map["answer"] = 42; printf( "The answer to life and everything is: %d\n", my_map["answer"] ); 
+9
Feb 01 '10 at 20:51
source share
+4
Feb 01 '10 at 20:49
source share

hash_map is a non-standard extension. unordered_map is part of std :: tr1 and will be moved to the std namespace for C ++ 0x. http://en.wikipedia.org/wiki/Unordered_map_%28C%2B%2B%29

+4
01 Feb '10 at 20:50
source share

The name adopted in TR1 (and a draft for the next standard) is std::unordered_map , so if you have this, it will probably be the one you want to use.

Also, using this is very similar to using std::map , provided that when / if you cross elements in std::map , they exit in the order specified by operator< , but for unordered_map, the order doesn't make sense at all.

+1
Feb 01 '10 at 20:52
source share



All Articles