2

Can someone give an example how to use hash_map in C++ with string as a key and integer as a value? Is something like hash_map h; a valid syntax? Do I explicitly have to define a hashing function or there is a predifined one for string keys?

3
  • 1
    Use std::unordered_map, not hash_map. Commented Sep 15, 2013 at 17:40
  • 1
    I know about it, but I want to be able to compile on compilers that do not support c++11. I participate in algorithms contests and I cant be sure that the test environments support the standart Commented Sep 15, 2013 at 17:43
  • 3
    C++11 has std::unordered_map, TR1 has std::tr1::unordered_map, Boost has boost::unordered_map. If the test environment supports neither, you'd have to implement your own. Commented Sep 15, 2013 at 17:51

1 Answer 1

1

Take a look at the documentation here, the example shown uses strings as keys and int as values (sometimes it is better to just check the docs first then ask here on so : D).

To be more precise:

  • you have to specify the key type, the value type, a hash function and a comparison function in the template
  • you can either construct your own hash function or use a default functor provided by the libs by instantiating a template for hash
  • for accessing the values just use the keys as if they were the index of an array

(I'm not pasting the code, you can find it in the documentation)

Sign up to request clarification or add additional context in comments.

2 Comments

Do you think the test environment will happen to have technology as outdated as the STL installed?
I do not know, I was sticking to the question desiderata : ) (Btw the story is the same, just check the documentation first)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.