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

C++Hashmap

C++ Problem Overview


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

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

#include <tr1/unordered_map> will get you next-standard C++ http://en.wikipedia.org/wiki/Unordered_map">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"] );

Solution 3 - C++

Solution 4 - C++

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

Solution 5 - C++

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionskydoorView Question on Stackoverflow
Solution 1 - C++anonView Answer on Stackoverflow
Solution 2 - C++Nikolai FetissovView Answer on Stackoverflow
Solution 3 - C++ManuelView Answer on Stackoverflow
Solution 4 - C++BenView Answer on Stackoverflow
Solution 5 - C++Jerry CoffinView Answer on Stackoverflow