目录
map
https://blog.csdn.net/qq_21997625/article/details/84672775
Map的使用:https://www.w3cschool.cn/cpp/cpp-fu8l2ppt.html
1、需要导入头文件
#include <map> // STL头文件没有扩展名.h
2、map 对象是一个模版类,需要关键字和存储对象两个模版参数
std::map<int , std::string> person;
3、可以对模版进行类型定义使其使用方便
typedef std::map<int , std::string> MAP_INI_STRING;
MAP_INI_STRING person;
一、map的构造
void map_constructor(){
//构造方式一:
map<int,string> intStr0;
map<int,string> intStr0_2 = map<int, string>();
//构造方式二:
//注意:C++11才开始支持括号初始化 使用{}赋值
map<int,string> intStr1_0 = map<int, string>{pair<int,string>(3,"world")};
map<int,string> intStr1_1 = map<int, string>{ {3,"world"}};
map<int,string> intStr1_2 = { {3,"world"}};
map<int,string> intStr1_3{ {3,"world"},{4,"earth"}};
}
二、增删改查
void map_zengShanGaiCha(){
//map的初始化
map<int,string> myMap = { {1,"张三"},{2,"李四"}};
//增
cout<<"-----------------增-----------------"<<endl;
myMap.insert(pair<int,string>(3, "王五"));
myMap.insert(map<int, string>::value_type(4,"谢六"));
myMap.insert({5,"田七"});
//使用[ ]进行单个插入,若已存在键值6,则赋值修改,若无则插入。
myMap[6] = "冯八";
//查
cout<<"-----------------查-----------------"<<endl;
string val1 = myMap[4];
auto it = myMap.find(4);
int key2 = it->first;
string val2 = it->second;
cout<<"val2 = "<<val2<<endl;
//改
cout<<"-----------------改-----------------"<<endl;
myMap[4] = "hehe";
cout<<"myMap[4] = "<<myMap[4]<<endl;
auto it2 = myMap.find(4);
it2->second = "ss";
cout<<"it2->second = "<<it->second<<endl;
//删
cout<<"-----------------删-----------------"<<endl;
myMap.erase(4);//通过key删除
myMap.erase(--myMap.end());//通过迭代器删除
myMap.erase(myMap.begin(),myMap.end());//清空(通过迭代器删除某一范围)
myMap.clear();
//大小
cout<<"-----------------大小-----------------"<<endl;
cout<<"size = "<<myMap.size()<<endl;
}
三、遍历
void map_enum(){
map<int, string> myMap={ { 5, "张大" },{ 6, "李五" },{3,"张三"},{4,"李四"}};
/**
遍历输出+迭代器的使用
auto自动识别为迭代器类型unordered_map<int,string>::iterator
迭代器就是一种指针的应用!
begin();是指第一个元素的位置
end()是指最后一个元素的后面
*/
//迭代器
auto iterBegin = myMap.begin();//指向第一个键值对的指针
auto iterEnd = myMap.end();//指向最后一个键值对的后面
iterEnd--;//指向最后一个元素
cout<<"iter1->first="<<iterEnd->first<<","<<"iter1->second="<<iterEnd->second<<endl;
//遍历方式一:
cout<<"---------------遍历方式一---------------"<<endl;
auto iter = myMap.begin();
while (iter!=myMap.end()) {
cout<<iter->first<<","<<iter->second<<endl;
iter++;
}
//遍历方式二:
cout<<"---------------遍历方式二---------------"<<endl;
for(auto it2=myMap.begin();it2!=myMap.end();it2++){
cout<<it2->first<<","<<it2->second<<endl;
}
//遍历方式三:
cout<<"---------------遍历方式三---------------"<<endl;
auto iter3 = myMap.begin();
for (int i=0; i<myMap.size(); i++,iter3++) {
cout<<iter3->first<<","<<iter3->second<<endl;
}
}
四、排序
void map_sort(){
//map是自带升序的
//unordered_map 是没有顺序的
map<int, string> myMap={ { 5, "张大" },{ 6, "李五" },{ 3,"张三"},{ 4,"李四"} };
for (auto it=myMap.begin(); it!=myMap.end(); it++) {
cout<<it->first<<","<<it->second<<endl;
}
}
行者常至,为者常成!