以上三种用法,虽然都可以实现数据的插入,但是它们是有区别的,当然了第一种和第二种在效果上是完成一样的,用insert函数插入数据,在数据的插入上涉及到集合的唯一性这个概念,即当map中有这个关键字时,insert操作是插入数据不了的,但是用数组方式就不同了,它可以覆盖以前该关键字对应的值,用程序说明
mapStudent.insert(map<int,
mapStudent.insert(map<int,
上面这两条语句执行后,map中这个关键字对应的值是“student_one”,第二条语句并没有生效,那么这就涉及到我们怎么知道insert语句是否插入成功的问题了,可以用pair来获得是否插入成功,程序如下
Pair<map<int,
Insert_Pair
我们通过pair的第二个变量来知道是否插入成功,它的第一个变量返回的是一个map的迭代器,如果插入成功的话Insert_Pair.second应该是true的,否则为false。
下面给出完成代码,演示插入成功与否问题
#include<map>
#include<string>
#include<iostream>
using
int
{
map<int,string>mapStudent;
pair<map<int,string>::iterator,bool>Insert_pair;
Insert_pair=mapStudent.insert(pair<int,string>(1,"student_one"));
if(Insert_pair.second==true)
{
cout<<"Insert
}
else
{
cout<<"Insert
}
Insert_pair
if(Insert_pair.second==true)
{
cout<<"Insert
}
else
{
cout<<"Insert
}
map<int,string>::iterator
for(iter=mapStudent.begin();iter!=mapStudent.end();iter++)
{
cout<<iter->first<<"
}
}
大家可以用如下程序,看下用数组插入在数据覆盖上的效果
#include<map>
#include<string>
#include<iostream>
using
int
{
map<int,string>mapStudent;
mapStudent[1]="student_one";
mapStudent[1]="student_two";
mapStudent[2]="student_three";
map<int,string>::iterator
for(iter=mapStudent.begin();iter!=mapStudent.end();iter++)
{
cout<<iter->first<<"
}
}
3. map的大小
在往map里面插入了数据,我们怎么知道当前已经插入了多少数据呢,可以用size函数,用法如下:
Int