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;
}

猜你喜欢

转载自blog.csdn.net/qq_39535750/article/details/80118637