map
map本质是一类关联式容器,属于模板类关联的本质在于元素的值与某个特定的键相关联,而并非通过元素在数组中的位置类获取。它的特点是增加和删除节点对迭代器的影响很小,除了操作节点,对其他的节点都没有什么影响。对于迭代器来说,不可以修改键值,只能修改其对应的实值。map内部数据的组织,map内部自建一颗红黑树(一种非严格意义上的平衡二叉树),这棵树具有对数据自动排序的功能,所以在map内部所有的数据都是有序的。
map接口
1、插入
用insert函数插入pair数据、用insert函数插入value_type数据和用数组方式插入数据
// 用insert函数插入pair数据
#include <map>
#include <string>
#include <iostream>
int main()
{
std::map<int, std::string> mapStudent;
mapStudent.insert(pair<int, std::string>(1, "student_one"));
mapStudent.insert(pair<int, std::string>(2, "student_two"));
mapStudent.insert(pair<int, std::stirng>(3, "student_three"));
std::map<int ,std::string>::iterator iter;
for(iter == mapStudent.begin(); iter != mapStudent.end(); iter++){
std::cout << iter->first << " " << iter->second << std::endl;
}
return 0;
}
// 用insert插入value_type数据
#include <map>
#include <string>
#include <iostream>
int main()
{
std::map<int, std::string> mapStudent;
mapStudent.insert(std::map<int, std::string>::value_type(1, "student_one"));
mapStudent.insert(std::map<int, std::string>::value_type(2, "student_two"));
mapStudent.insert(std::map<int, std::string>::value_type(3, "student_three"));
std::map<int ,std::string>::iterator iter;
for(iter == mapStudent.begin(); iter != mapStudent.end(); iter++){
std::cout << iter->first << " " << iter->second << std::endl;
}
return 0;
}
// 用数组的方式插入数据
#include <map>
#include <string>
#include <iostream>
int main()
{
std::map<int, string> mapStudent;
mapStudent[1] = "student_one";
mapStudent[2] = "student_two";
mapSutdent[3] = "student_three";
std::map<int, string>::iterator iter;
for(iter == mapStudent.begin(); iter != mapStudent.end(); iter++){
std::cout << iter->first << " " << iter->second << std::endl;
}
return 0;
}
2、删除
// 用erase删除map中的元素
#include <map>
#include <string>
#include <iostream>
int main()
{
std::map<int, std::string> mapStudent;
mapStudent[1] = "student_one";
mapStudent[2] = "student_two";
mapStudent[3] = "student_three";
mapStudent[4] = "student_four";
std::map<int, std::string>::iterator iter = mapStudent.begin();
for(;iter != mapStudent.end();){
if((*iter).second == "student_one"){
mapStudent.erase(iter++);
}else{
++iter;
}
}
for(iter == mapStudent.begin(); iter != mapStudent.end(); iter++){
std::cout << iter->first << " " << iter->second << std::endl;
}
return 0;
}
// 注意:
// mapStudent.erase(iter++);中的iter++,不是earse(iter),
// 然后iter++。因为iter指针被erase之后就失效了,不能再用iter++;
// 也不是erase(++iter),这样就不是删除iter原来指向的元素了。