版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/89811332
一 用pair判断insert到map的数据是否插入成功
1 代码
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main(){
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 Successfully"<<endl;
}
else{
cout<<"Insert Failure"<<endl;
}
insert_pair = mapStudent.insert(pair<int, string>(1, "student_two"));
if(insert_pair.second == true){
cout<<"Insert Successfully"<<endl;
}else{
cout<<"Insert Failure"<<endl;
}
map<int, string>::iterator iter;
for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++){
cout<<iter->first<<" "<<iter->second<<endl;
}
return 0;
}
2 运行
[root@localhost charpter03]# g++ 0321.cpp -o 0321
[root@localhost charpter03]# ./0321
Insert Successfully
Insert Failure
1 student_one
3 说明
用pair判断insert到map的数据是否插入成功。pair变量insert_pair中的第一个元素的类型是map<int,string>::iterator,是和即将判断的map中的key、value类型一致的一个map的迭代器。如果insert成功了,则insert_pair.second的结果为true,否则为false。同一个key已经有了数据之后,再insert就会失败。而数组插入的方式,则是直接覆盖。
二 数组方式插入map覆盖原有的数据
1 代码
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
map<int,string> mapStudent;
mapStudent[1] = "student_one";
mapStudent[1] = "student_two";
mapStudent[2] = "student_three";
map<int, string>::iterator iter;
for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++){
cout<<iter->first<<" "<<iter->second<<endl;
}
return 0;
}
2 运行
[root@localhost charpter03]# g++ 0322.cpp -o 0322
[root@localhost charpter03]# ./0322
1 student_two
2 student_three
3 说明
展示了mapStudent[1]上已经有数据“student_one”了,再用语句:
mapStudent[1]=“student_two";
就可以直接覆盖成功。