map容器的四种插入元素方法
//插入元素 //四种插入方法比较void display(){map m;pair::iterator,bool> pair1 ,pair2,pair3;//1.方法pair1 = m.insert(pair(1,"teacher01"));pair2 = m.insert(pair(2,"teacher02"));pair3 = m.insert(pair(2
·
//插入元素 //四种插入方法比较
void display()
{
map<int,string> m;
pair<map<int,string>::iterator,bool> pair1 ,pair2,pair3;
//1.方法
pair1 = m.insert(pair<int,string>(1,"teacher01"));
pair2 = m.insert(pair<int,string>(2,"teacher02"));
pair3 = m.insert(pair<int,string>(2,"teacher02"));
if (pair2.second)
{
cout<<"2 teacher02插入成功"<<endl;
cout<<pair2.first->first<<":"<<pair2.second<<endl;
}
else
{
cout<<"2 teacher02插入失败"<<endl;
cout<<pair2.first->first<<":"<<pair2.second<<endl;
}
if (pair3.second)
{
cout<<"2 teacher02插入成功"<<endl;
cout<<pair3.first->first<<":"<<pair3.second<<endl;
}
else
{
cout<<"2 teacher02插入失败"<<endl;
cout<<pair3.first->first<<":"<<pair3.second<<endl;
}
//2.方法
m.insert(make_pair(3,"teacher03"));
m.insert(make_pair(4,"teacher04"));
//3.方法
m.insert(map<int,string>::value_type(5,"teacher05"));
m.insert(map<int,string>::value_type(6,"teacher06"));
//4. 如果key相等 会修改对应的value
m[7] = "teacher07";
m[8] = "teacher08";
m[0] = "teacher09";
m[0] = "teacher00";
//遍历
for (map<int,string>::iterator it = m.begin();it!=m.end();it++)
{
cout<<(*it).first<<endl;
cout<<(*it).second<<endl;
}
while (!m.empty())
{
map<int,string>::iterator it = m.begin();
cout<<it->first<<"\t"<<it->second<<endl;
m.erase(it);
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)