I insert a pair (key,value) to my hashmap but it seems like it doesn’t have the value when trying to print it
The thing is i don’t know why i can’t print the second element in the following code.
Let’s see some code :
.h
typedef hash_map<const string, string, strptrhash, strptrequal> StringHashMap;
StringHashMap m_memberNameMap;
typedef pair <const string,string> string_pair;
.cpp
void Powerdomain::addMemberName(const string& name){
if (m_memberNameMap[name]==""){
m_memberNameMap.insert(string_pair(name,name));
StringHashMap::iterator it = m_memberNameMap.begin();
cout << it->first << endl;
cout << it->second << endl;
cout << m_memberNameMap["MD1"] << endl;
}
with name=”MD1″ this outputs :
MD1
*blank*
*blank*
EDIT
concerning the answer of Alan :
ModuleType * moduletype4=new ModuleType("type4");
ModuleType * value = moduleTypeMap["type4"];
if (value==NULL) {
ModuleType& value2=*moduleTypeMap["type4"];
value2=*moduletype4;
cout << "correctly inserted" << endl;
}
cout << moduleTypeMap["type4"]->getName() << endl;
This doesn’t work. I Might be confused now !
What does
m_memberNameMap[name]do in theifcondition? If the keynamedoesn’t exist in the map, it creates a new slot with that key, and value equal to empty string.That is, the expression
m_memberNameMap[name]invokesoperator[]which inserts an item equal tostring_pair(name, "")to the map if the keynamedoesn’t exist,The solution is to use
findas:Instead of
insertfunction, you can also use :After all,
operator[]creates a new slot if the key doesn’t exist.