Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple hashmap implementation in C++

I'm relatively new to C++. In Java, it's easy for me to instantiate and use a hashmap. I'd like to know how to do it in a simple way in C++, since I saw many different implementations and none of them looked simple to me.

like image 243
Paulo Guedes Avatar asked Nov 05 '08 18:11

Paulo Guedes


People also ask

Can we use HashMap in C?

Hash Table is a data structure which stores data in an associative manner. In hash table, the data is stored in an array format where each data value has its own unique index value. Access of data becomes very fast, if we know the index of the desired data.

How is HashMap implemented in C ++?

There are two common styles of hashmap implementation: Separate chaining: one with an array of buckets (linked lists) Open addressing: a single array allocated with extra space so index collisions may be resolved by placing the entry in an adjacent slot.

Does C have hash table?

A Hash Table in C/C++ (Associative array) is a data structure that maps keys to values. This uses a hash function to compute indexes for a key.

How is hash table implemented?

Hashing is implemented in two steps: An element is converted into an integer by using a hash function. This element can be used as an index to store the original element, which falls into the hash table. The element is stored in the hash table where it can be quickly retrieved using hashed key.


1 Answers

Most compilers should define std::hash_map for you; in the coming C++0x standard, it will be part of the standard library as std::unordered_map. The STL Page on it is fairly standard. If you use Visual Studio, Microsoft has a page on it.

If you want to use your class as the value, not as the key, then you don't need to do anything special. All primitive types (things like int, char, bool and even char *) should "just work" as keys in a hash_map. However, for anything else you will have to define your own hashing and equality functions and then write "functors" that wrap them in a class.

Assuming your class is called MyClass and you have already defined:

size_t MyClass::HashValue() const { /* something */ } bool MyClass::Equals(const MyClass& other) const { /* something */ } 

You will need to define two functors to wrap those methods in objects.

struct MyClassHash {   size_t operator()(const MyClass& p) const {     return p.HashValue();   } };  struct MyClassEqual {   bool operator()(const MyClass& c1, const MyClass& c2) const {     return c1.Equals(c2);   } }; 

And instantiate your hash_map/hash_set as:

hash_map<MyClass, DataType, MyClassHash, MyClassEqual> my_hash_map; hash_set<MyClass, MyClassHash, MyClassEqual> my_hash_set; 

Everything should work as expected after that.

like image 144
hazzen Avatar answered Sep 24 '22 02:09

hazzen