参考博客:(99条消息) std map用法_alex1801的博客-CSDN博客_std::map用法
(99条消息) C++ map遍历_两鬓已不能斑白的博客-CSDN博客_c++ map 遍历
对于stl的容器,平时对于map用的相对较少,今天刷题的时候碰到了这个数据结构,记录一下
map的基础属性:
m.size(); // 实际数据的数据
m.max_size(); // 最大数据的数量
m.empty(); // 判断容器是否为空
Amap m1, m2;
m1[1] = a1;
m1[2] = a2;
m1[3] = a3;
m2.insert(m1.begin(), m1.end());
Amap mp2(m1); // mp2是m1的副本(通过拷贝构造)
m2 = m1; // m2是mp1的副本(通过复制赋值)
插入,我一般这么用
m.insert(make_pair(2, "Two"));
若已存在该键值,再进行插入操作无效,不报错,只能通过赋值改变内容
map的迭代器
begin: 返回迭代器到开始(公共成员函数)
end: 返回迭代器到末尾(公共成员函数)
rbegin:返回反向迭代器到反向开始(公共成员函数)
rend: 返回反向迭代器到反向端(公共成员函数)
cbegin: 将const_iterator返回到开始(公共成员函数)
cend: 返回const_iterator末尾(公共成员函数)
crbegin: 返回const_reverse_iterator到反向开始(公共成员函数)
crend: 返回const_reverse_iterator到reverse end(公共成员函数)
map<int, string>::iteartor it
for (auto it = m.begin(); it != m.end(); ++it)
{
cout << " first:" << it->first << " " << it->second << endl;
}
//当然遍历的时候这么做更好
#include <iostream>
#include <map>
using namespace std;
int main() {
map<int, int> _map;
_map[0] = 1;
_map[1] = 2;
_map[10] = 10;
map<int, int>::iterator iter;
iter = _map.begin();
while(iter != _map.end()) {
cout << iter->first << " : " << iter->second << endl;
iter++;
}
// 也可以使用for循环遍历
/*
for(iter = _map.begin(); iter != _map.end(); iter++) {
cout << iter->first << " : " << iter->second << endl;
}
*/
return 0;
}
上图为顺序迭代
下图为逆序迭代
for (auto it = m.rbegin(); it != m.rend(); ++it)
{
cout << " first:" << it->first << " " << it->second << endl;
}
当你需要了解map中的key值是否存在时:
m.find(key) != m.end() // key值存在
auto it = m.find(1);
cout << " m.find: " << it->first << endl;
如果你需要移除key
m.eraser(key)