STL - map 常用用法详解


STL 通用函数总结
1.头文件:

#include<map>

2.定义:建立Key - value的对应

map<int, string> mapStudent; //定义一个用int作为索引,并拥有相关联的指向string

3.常用操作:
3.1在map中插入元素

mapStudent.insert(pair<int, string>(1, “One”));//用insert方法插入pair对象
mapStudet.insert(map<int, string>::value_type (1, “One”));//用insert方法插入value_type对象
mapStudent[1]:”ONE”;//用数组方式
mapStudent[2]=”TWO”;

3.2.从map中删除元素:

iterator erase(iterator it); //通过一个条目对象删除
iterator erase(iterator first, iterator last); //删除一个范围
size_type erase(const Key& key); //通过关键字删除

3.3.find(key),返回pair类型指针
4.举例:

#include <string>
#include <map>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    map<int,char> mapa;//定义map函数
    mapa.insert(map<int,char>::value_type(1,'c'));//插入元素
    mapa.insert(map<int,char>::value_type(2,'d'));
    mapa.insert(pair<int,char>(3,'a'));
    mapa[4]='b';
    map<int,char>::iterator it=mapa.find(1);//查找元素
    cout<<it->first<<" "<<it->second<<endl;
    mapa.erase(it);//删除元素
    mapa.erase(2);
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值