C++的Map常见用法总结

xiaoxiao2021-02-28  20

Map是STL的非常重要的关联容器,其底层由红黑树实现,是一种key+value的模式。

①头文件和定义:

#include <map> typedef map<string, int> My_map; //第一种定义方式:模板定义 My_map MMap; //这两种定义方法均可 map<string, int> Map; //第二种定义方式:直接定义

②迭代器和遍历:

map<string, int>::iterator map_it; //定义一个迭代器 for (map_it = Map.begin(); map_it != Map.end(); map_it++) {} //遍历map

③修改数据: insert();

Map.insert({ "b",2 }); //使用这种插入的方式 Map.insert(map<string, int>::value_type("b", 2)); Map.insert(pair<string, int>("c", 3)); Map.insert(make_pair<string, int>("d", 4)); int i = 0; //修改值的写法 Map["a"] = i; map<string, int>::iterator map_ptr; map_ptr=Map.find("b"); cout << map_ptr->second << endl;//迭代器指针里的first指的是key,second指的是value map_ptr->second = 3; //可以通过这种方式进行修改

④遍历: .begin()迭代器遍历

     迭代器在使用时一定注意,一定要使用的时候设迭代器,不要提前设好,如果在设置好迭代器之后再对原容器进行操作,迭代器就不能发挥效果了。

map<string, int>::iterator map_it; //定义一个迭代器 for (map_it = Map.begin(); map_it != Map.end(); map_it++) {} //遍历map

 ⑤删除数据:erase()

auto iter = Map.begin(); //定义迭代器 iter=Map.erase(iter); //这样即便删除了头,iter会自动返还头下一个位置的值,不会出现直接断裂的情况

 ⑥基础信息:

Map.size();//得到尺寸,为key的尺寸 Map.empty(); //空为1,非空为0 Map.clear(); //清空所有数据
转载请注明原文地址: https://www.6miu.com/read-2595537.html

最新回复(0)