Can someone please give me an example of how to use .find() with a hashmap?

This is what I have:
(wordData is a struct with info about each word, and hashFunc is the name of the hash function)
typedef hash_map<string,wordData,hashFunc> wordHash;

wordHash hashofwords;

(after passing in a string s to a function)
hash_map<string, wordData>::iterator it;
it = hashofwords.find(s);

if(it != hashofwords.end()){
//do whatever

I know something is wrong in my thinking but I'm not sure what it is.

8 Years
Discussion Span
Last Post by sidatra79

What about:

//typedef hash_map<string,wordData,hashFunc> wordHash;
//-->because i dont know your much things about your wordData...I am using int as an example
typedef hash_map<std::string,int> map_type;

//wordHash hashofwords;
map_type my_map;
my_map[ "foo" ] = 3;
my_map[ "socrates" ] = 7;
//(after passing in a string s to a function)
//hash_map<string, wordData>::iterator it;
//it = hashofwords.find(s);
//if(it != hashofwords.end()){
//do whatever
//sth like:
map_type::iterator itr1;
itr1=map.find("fo");        //I think one of your mistakes was here for sure: U forgot ""
//and u might use sth like:
if ( itr1== my_map.end() ) 
    std::cout <<"Couldn't find an entry for 'fo'\n"; 
    std::cout <<"Entry in map for key '" 
              <<" is " 

The hash_map::find() method takes a reference to a key as its argument, and returns an iterator which points to the end of the container on failure, or to a key/value pair on success. This pair is stored in an std::pair object, which allows u to access the elements with the first and second members of that object like u can see above.

However I am neither 100% sure.. nor can I test it here where I am ... :D
Hope it helps.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.