C++用map插入实战

一 用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";

就可以直接覆盖成功。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值