C++标准模板库学习(二)---map的初步使用

map相当于建立了一个键值对的映射,剩下的跟vector有些类似。但是map中的key值是不允许重复的。

今天学习了map的增删改查操作。

#include <iostream>

#include <map>

//map的示例
using namespace std;

int main()
{
    //map的功能是自动建立key值到value值的对应
    //查找的复杂度是log(N)

    //定义map,map中的key值不允许有重复!!!
    map<int,char> map_sample;

    //使用模板类进行类型定义
    typedef map<int,char> MAP_SAMPLE_INT_CHAR;
    MAP_SAMPLE_INT_CHAR map_sample2;

    //插入元素
    map_sample2.insert(map<int,char>::value_type(1,'a'));
    map_sample2.insert(map<int,char>::value_type(2,'b'));
    cout<<"共有元素个数:"<<map_sample2.size()<<endl;
    //根据key查找元素并且判断一个元素是否存在,并删除该元素
    map<int,char>::iterator it = map_sample2.find(1);
    if(it==map_sample2.end())
    {
        cout<<"没有找到!"<<endl;
    }
    else//注意,second 是存储的数据
    {
        cout<< "找到,存储的数据是" << it->second<<endl;
        map_sample2.erase(it);//删除之
    }

    cout<<"共有元素个数:"<<map_sample2.size()<<endl;

    //修改元素
    it = map_sample2.find(2);
    if(it==map_sample2.end())
    {
        cout<<"没有找到!"<<endl;
    }
    else//注意,second 是存储的数据
    {
        cout<< "找到,存储的数据是" << it->second<<endl;
        it->second = 'c';//直接修改
    }

    it = map_sample2.find(2);
    if(it==map_sample2.end())
    {
        cout<<"没有找到!"<<endl;
    }
    else//注意,second 是存储的数据
    {
        cout<< "找到,存储的数据是" << it->second<<endl;
    }



    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值