tags:

views:

536

answers:

5

Hi,

I heard a lot about hash function but I don't know how to use it in C++. I learnt that we can use hash_map. Does g++ support that by simply including #include <hash_map>? Can anybody offer me a simple example using hash_map?

Thanks a lot!

+3  A: 

Wikipedia never lets down:

http://en.wikipedia.org/wiki/Hash_map_(C%2B%2B)

Manuel
+1  A: 

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

Ben
+5  A: 

The current C++ standard does not have hash maps, but the coming C++0x standard does, and these are already supported by g++ in the shape 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;
}

In order to get this compile, you need to tell g++ that you are using C++0x:

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

These maps work pretty much as std::map does, except that instead of providing a custom operator<() for your own types, you need to provide a custom hash function - suitable functions are provided for types like integers and strings.

anon
+1 : you should edit that answer to mention TR1 though...
Kornel Kisielewicz
@Kornel No, I shouldn't. TR1 was never ratified - the tr1 namespace is just an extension some compiler provide. I never use it in my own code.
anon
@Neil, sooo, a person using GCC 3.4, MSVC and other non-C++0x compilers should not use TR1, but gratiously wait until C++0x library extensions are supported out of the box?
Kornel Kisielewicz
@Kornel They certainly can use TR1, but I don't use VC++ so cannot in all conscience edit my answer to suggest they do so. To be really safe, which is what most of my code does, don't use unordered maps. It depends how portable you want your code to be.
anon
@Neil, hmm, point taken, however in that case, wouldn't it be acceptable to point to Boost.Unordered, that is added to the working draft of the C++0x standard?
Kornel Kisielewicz
A: 

#include <tr1/unordered_map> will get you next-standard C++ unique hash container. Usage:

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"] );
Nikolai N Fetissov
C-style output with C++-style containers? Ouch!
Bill
Welcome to the real world :)
Nikolai N Fetissov
+1  A: 

The name accepted into TR1 (and the draft for the next standard) is std::unordered_map, so if you have that available, it's probably the one you want to use.

Other than that, using it is a lot like using std::map, with the proviso that when/if you traverse the items in an std::map, they come out in the order specified by operator<, but for an unordered_map, the order is generally meaningless.

Jerry Coffin