Reputation: 22519
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?
Upvotes: 0
Views: 10606
Reputation: 31
Iterate your hashmap, vector, list and other structures:
for(hash_map<string,int>::iterator i = dict.begin(); i != dict.end(); i++)
{
cout << "key(string): " << i->first << ", value(int): " << i->second << endl;
}
Upvotes: 0
Reputation: 44742
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)
Upvotes: 9