STL容器:map

1.基本用法:

  • #include<map> 需要头文件。

  • map<key_value,int>mp 创建一个以 key_value 类型为数组下标,存储32位整数类型的 map

  • map[value] 数组操作,可以直接修改或查询元素。

2.需要用的iterator的操作

  1. 前向迭代器遍历:
map <int,int>::iterator it;
map <int,int>::iterator itEnd;
it = mapPerson.begin();//指向头元素
itEnd = mapPerson.end();//指向头元素后面的元素
while (it != itEnd) {
    cout<<it->first<<' '<<it->second<<endl;  
    it++;
}
  1. find函数(括号内填的是键值

该方法与直接使用数组的区别是可以返回迭代器。

map<int,int>mapPerson;
map<int,int>::iterator it;
it=mapPerson.find(114514);
if(it==mapPerson.end()){
    cout<<"No such member";
}else{
    cout<<it->second;
}
  1. 删除元素
map<int,int>mapPerson;
erase(it)//删除迭代器为it的元素
erase(it1,it2)//删除迭代器it1和it2之间的元素
erase(key_value)//删除键值为key_value的元素
clear()//清空

3.其他操作

  • .empty() 是否为空

  • .count() 指定元素出现次数

  • .lower_bound() 向上查找大于等于给定键值的元素迭代器

  • .upper_bound() 向上查找严格大于给定键值的元素迭代器

posted @ 2023-03-19 10:13  MornHus  阅读(22)  评论(0)    收藏  举报