(一)了解map
map是有序(默认升序)不重复的key-value对(关联容器,不同于顺序容器)
其底层存储结构为红黑树。key不允许重复
(二)Test_Demo
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
/*******************************Demo1 define map********************************/
map<int, string> m;
map<int, string> m1{ {1, "log1"}, {2, "log2"} };
map<int, string> m2(m1);
map<int, string> m3 = { {3, "log3"}, {2, "log2"} };
/*******************************Demo2 options***********************************/
//遍历:正反向,const,数组
cout << "m1:" << endl;
for (map<int, string>::iterator it = m1.begin(); it != m1.end(); ++it) {
cout << it->first << "," << it->second << endl;
}
//map是有序(默认升序)不重复的key-value对(关联容器,不同于顺序容器),输出是升序输出
cout << "m3:" << endl;
for (map<int, string>::iterator it = m3.begin(); it != m3.end(); ++it) {
cout << it->first << "," << it->second << endl;//有序特性
}
//for (int i = 0; i < m3.size(); ++i) {
// cout << m3[i] << endl;//有序特性
//}
//插入
cout << "第一种插入方式:pair" << endl;
auto status = m1.insert(pair<int, string>(3, "log1"));
if (status.second == true) {
cout << "insert successful!" << endl;
}
status = m1.insert(pair<int, string>(3, "log1"));
if (status.second == false) {//不重复特性
cout << "insert failed!" << endl;
}
for (map<int, string>::iterator it = m1.begin(); it != m1.end(); ++it) {
cout << it->first << "," << it->second << endl;
}
cout << "第二种插入方式:map<int, string>::value_type" << endl;
status = m1.insert(map<int, string>::value_type (4, "log4"));
if (status.second == true)
cout << "insert successful!" << endl;
else
cout << "insert failed!" << endl;
for (map<int, string>::iterator it = m1.begin(); it != m1.end(); ++it) {
cout << it->first << "," << it->second << endl;
}
cout << "第三种插入(修改)方式:下标" << endl;
m1[2] = ("log111"); //即使重复也会插入成功,但是会覆盖掉原有的数据(谨慎使用)
for (map<int, string>::iterator it = m1.begin(); it != m1.end(); ++it) {
cout << it->first << "," << it->second << endl;
}
//删除
m1.erase(1);
auto m_clone = m1;//拷贝构造
m1.clear();
if (m1.empty())
cout << "m1 is empty!" << endl;
for (map<int, string>::iterator it = m_clone.begin(); it != m_clone.end(); ++it) {
cout << it->first << "," << it->second << endl;
}
//查找数据
auto it = m_clone.find(2); //若查找一个不存在的key,会发生运行时错误
cout << it->first << "," << it->second << endl;
//m_clone.lower_bound();
//m_clone.upper_bound();
return 0;
}