c++ map的学习

学习自
https://www.cnblogs.com/fnlingnzb-learner/p/5833051.html

1.map中关键字与存储对象的值是一对一的关系,它实际上是一颗红黑树,所以其中的元素是有序的,并且默认是升序,这个和sort函数 的默认排序是一样的。可以修改存储对象的值,但是不能修改关键字的值。
2.使用关键字搜索,搜素的时间复杂度是 lg(n) 。
3. 如何定义

map <int,string> map1;//定义了一个 关键字为 int 存储对象值为 string的map

4 如何使用
最简单的方法是当做数组使用:
初始化:

map1[0] = "studentone";//只填充存储对象的关键字的值。
map1[1] = "studenttwo";

使用insert()插入pair数据
初始化:

map1.insert(pair( <int, string>(1,"studentone"));//比较难记,尤为注意这个pair数据。

使用pair插入数据时无法修改已有关键字对应的存储对象的值。如果关键字不存在 插入就是成功的,返回值为true,否则为false;
代码如下:

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;  

5。遍历:
使用数组法遍历:

//和插入类似,直接输出其存储对象即可。
cout<<map1[0]<<endl;

使用前向迭代器:

map <int,string> iterator it;
for(it = map1.begin();it!= map1.end();it++){
    cout<< it->first <<' '<<it -> second <<endl;
}

使用后向迭代器:

map <int , string> iterator it;
for(it = map1.rbegin();it!=map1.rend();it++){
    cout<< it->first <<' '<<it -> second <<endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值