双11狂欢大促

盲盒赢 定制羽绒服

开启惊喜盲盒,抽取你的专属好礼

— 惊喜奖品抢先看 —

Help !高手过来看看 STL map 插入出错

miker86 miker86 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
#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;

void InitData()
{
for (int i = 0; i < 5; 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;
}

以上代码有个问题我在InitData()里面初始化一个全局map变量atrributeMap_g, 但是在PrintData()里面却得不到我刚才插入的元素,有时候是乱码,有时候只有一个值而且都是最后一个插入的值,前面的值都被冲调了。我查了些资料说是map的kay一定要不一样,代码里面是const char*, 每次比较的是字符串地址,而且每次该地址都是一样的,所以插入只会更新value值。
但是我想在不改变struct 定义的情况下,试图把const char* 的字符串的值作为Key插入,即:std::string strName(atrr.name), 然后以该字符串作为Key 插入到map里仍然和前面的情况一样。请问在不改变struct 和 map 定义的情况下,怎样正确循环插入元素。
...全文

相关推荐

评论 7
收藏 已收藏
分享
返回顶部
miker86
C++ 语言 65,214 成员 250,514 内容