Hashes in C++

Dear all,
I just shifted to c++ from perl programming, I was just searching if we have some variables in c++ working similar to hashes in perl. If so, can we assign an array to a key of hash? I did this is perl. I will really appreciate your valuable comments in this regard.

Thanks,
Rahul
Last edited on
Yes, indeed! In C++, if you include the header <map>, then you'll gain access to the std::map class. You can instantiate it as so:

std::map<key_type,value_type> name;

Now, I suppose you could assign an array to a key of a hash, BUT unless you want to deal with a bit of headache, make sure that your map has a way "properly" checking the array (== with pointers does something else). For that, I'd suggest using std::vectors instead of pure C arrays (#include <vector>, instantiate with std::vector<element_type> name;).

You can access individual elements of a map with via name[key], and in this regard it works very similarly to Perl's hashes: if the key exists, a reference to its value is returned, if not then the key/value pair is automatically created.

For more info:
http://www.cplusplus.com/reference/stl/map/

-Albatross
Last edited on
If you want to use an actual hash, you might want to consider using the TR1 unordered_map rather than map (pre-TR1 unordered_map was sometimes available as hash_map.)

Note that if your key is a custom type, you will probably have to provide a custom hashing function.

I usually use the regular map, but switch to unordered_map when handling a lot of entries.

Andy
Last edited on
Thank you so much Albatross and Andy for your valuable comments :)

Best wishes,
Rahul
Topic archived. No new replies allowed.