tags:

views:

225

answers:

2

Here's what I have, I am new to C++ so I am not sure if this is right...

typedef pair<string, int>:: make_pair;
hash_map <string, int> dict;
dict.insert(make_pair("apple", 5));

I want to give my hash_map "apple", and I want to get back 5. How do I do it?

+7  A: 

hash_map is not standard C++ so you should check out the documentation of whatever library you're using (or at least tell us its name), but most likely this will work:

hash_map<string, int>::iterator i = dict.find("apple");

if (i == dict.end()) { /* Not found */ }
else { /* i->first will contain "apple", i->second will contain 5 */ }

Alternatively, if you know for sure that "apple" is in dict, you can also do: dict["apple"]. For example cout << dict["apple"]; will print out 5.

Also, why the typedef in your code? Can't you just use std::make_pair? And, it won't compile the way you wrote it (with the two leading colons)

Andreas Bonini
+1 If you *know* that `dict` contains apple, you can also use `dict["apple"]`. This can be slightly less efficient, but more clear in certain situations.
Andreas Brinck
Added to my reply, thanks
Andreas Bonini
Presumably hash_map works like map, and if the key is not already present, it will add it with value 0. It does in the SGI hash_map, anyway.
Steve Jessop
A: 

Also, why the typedef in your code? Can't you just use std::make_pair? And, it won't compile the way you wrote it (with the two leading colons)

How should I write that line?

SuperString
nvm got it thanks!
SuperString