STL:map用法总结

一:介绍

map是STL的关联式容器,以key-value的形式存储,以红黑树(平衡二叉查找树)作为底层数据结构,对数据有自动排序的功能。
命名空间为std,所属头文件<map>

二:常用操作

容量:
a.map中实际数据的数据:map.size()
b.map中最大数据的数量:map.max_size()
c.判断容器是否为空:map.empty()

修改:
a.插入数据:map.insert()
b.清空map元素:map.clear()
c.删除指定元素:map.erase(it)

迭代器:
a.map开始指针:map.begin()
b.map尾部指针:map.end() 注:最后一个元素的下一个位置,类似为NULL,不是容器的最后一个元素

三:存储

1     //方法1:
2     map1.insert(pair<int, string>(2, "beijing"));
3     //方法2:
4     map1[4] = "changping";
5     //方法3:
6     map1.insert(map<int, string>::value_type(1, "huilongguan"));
7     //方法4:
8     map1.insert(make_pair<int, string>(3, "xierqi"));

四:遍历

1     for (map<int, string>::iterator it=map1.begin(); it!=map1.end(); it++)
2     {
3         cout << it->first << ":" << it->second << endl;
4     }

五:查找

 1     //方法1
 2     string value1 = map1[2];
 3     if (value1.empty())
 4     {
 5         cout << "not found" << endl;
 6     }
 7 
 8     //方法2
 9     map<int, string>::iterator it = map1.find(2);
10     if (it == map1.end())
11     {
12         cout << "not found" << endl;
13     }
14     else
15     {
16         cout << it->first << ":" << it->second << endl;
17     }

六:修改

map1[2] = "tianjin";

七:删除

1     //方法1
2     map1.erase(1);
3 
4     //方法2
5     map<int, string>::iterator it1 = map1.find(2);
6     map1.erase(it1);

猜你喜欢

转载自www.cnblogs.com/woniu201/p/9876955.html