Hello all. I'm quite new to C++'s implementation of hash maps. I've messed around with them in Java, which seems really simple compared to this, but I want to try to figure them out in C++ as well.
So I found some code on a website that got me started, but there are some things I don't understand. Here's the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
#include <hash_map>
#include <string>
#include <iostream>
#define _DEFINE_DEPRECATED_HASH_CLASSES 0
using namespace std;
using namespace stdext;
int main()
{
hash_map<string, int> yeah;
string hello = "hello";
yeah["hello"] = yeah.comp("hello");
yeah["Mellow Gold"] = 233;
if (yeah["mellow Gold"])
cout << "YEY!" << endl;
cout << yeah.comp("hello");
cout << yeah["hello"];
yeah["okay"] = 23;
cout << endl << yeah["okay"] << endl;
return 0;
}
| |
There are some things I don't understand:
- Why is there the "#define _DEFINE...?" Is it defining something that is used in the hash_map lib or what?
- What's stdext? And I guess it's used so I don't have to do stdext:: everytime I want to use a member of that namespace?
- I'm not really sure how to call the hash function/create my own. I want to hash on the string values, so if I do "yeah.comp("hello")," that returns the hash value and stores it for yeah["hello"], right? Is that the right way of doing it?
What I really want to do is build a dictionary of words, so I will have strings (that will be my words), and I want to count how many times these words occur in my text file. I'm choosing a hash_map because of how fast the look up is. I'm just stuck on how I implement this.
My current thought process/problem is... I want to basically have a struct that just has my word and its count, but when I go to put this in the hash map, I'm not really sure how I do this, since I don't want the hash function to hash on the whole struct, I just want the string's value to hash. So let's say I have a struct that looks like this:
1 2 3 4
|
struct word {
string myWord;
int count = 0;
};
| |
Then do I declare the hash_map like:
|
hash_map<word, int, hash<word::myWord>, hash_compare<word::myWord, less<word::myWord>>> myHash;
| |
I know hash_map's 3rd argument is the hash function and the 4th argument is to check whether two keys are equal, but as you can see, I'm not really sure how to use these...
I'm sure this is really confusing, so please ask me questions so I can clarify.