#include <string>
#include <map>
#include <iostream>
using namespace std;
struct arrtibute
{
const char* name;
int id;
};
typedef std::map <std::string, arrtibute*> AtrributMap;
AtrributMap atrributeMap_g;
const int MaxCount = 3;
void InitData()
{
for (int i = 0; i < MaxCount; i++)
{
static arrtibute atrr;
std::string str;
cout < <"Input the name: ";
cin>>str;
atrr.id = i;
atrr.name = str.c_str();
std::pair <AtrributMap::iterator,bool> insResult;
insResult = atrributeMap_g.insert(std::make_pair(atrr.name, &atrr));
// Make sure added successfully
if (!insResult.second)
{
cout < <"insert to transfer map failed, id and name is: "
< <atrr.id < <" " < <atrr.name < <endl;
}
}
}
void PrintData()
{
cout < <"**********print the map*********" < <endl;
AtrributMap::const_iterator Itor;
for( Itor = atrributeMap_g.begin();
Itor != atrributeMap_g.end();
++Itor )
{
cout < <"name is: " < <Itor->second->name < <" " < <"Id is : " < <
Itor->second->id < <endl;
}
cout < <"**********end of the map*********" < <endl;
}
The above code have a problem: I insert 3 iterm into the global map atrributeMap_g, when I output the map there is an error:
all the 3 item have different value but the same id which is the last time insert id. I think this may caused by the key:atrr.name.
Since atrr.name is const char* which compare with the address in map key compare implementation, but I want to compare the string.
So I try to do std::string strName(atrr.name) to convert const char* to std::string then atrributeMap_g.insert(std::make_pair(strName, &atrr)),
but this take no effect.
How to loop to insert correctly under the conditon that do not change the definition of struct arrtibute and map AtrributMap.
Thanks a lot!