开发者

value of a hash map element not printing properly

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, strptre开发者_JAVA技巧qual> 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 the if condition? If the key name doesn'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] invokes operator[] which inserts an item equal to string_pair(name, "") to the map if the key name doesn't exist,

The solution is to use find as:

if (m_memberNameMap.find(name) == m_memberNameMap.end())
{
    m_memberNameMap.insert(string_pair(name,name));
    //rest of the code...
}

Instead of insert function, you can also use :

   m_memberNameMap[name] = name; //simpler, cute!

After all, operator[] creates a new slot if the key doesn't exist.


There are several misconceptions here. First, using the operator[] in the map, will actually insert a new (empty) element with the key name. The semantics of this operator are that if you access an element inside the map, it has to be there, so if it doesn't exist, it is created. Then, the insert operation is defined to not to add the element if it already exists, so this is your problem.

You should be using find first:

if (m_memberNameMap.find(name) == m_memberNameMap.end()) // don't exist
{
   // rest of your code
}


Or if you want to use operator [], you can just save its result to ensure only one lookup occurs:

string & value = m_memberNameMap[name];
if (value.empty()) {
   value = name;
   // ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜