map
一、map的简介
1、map是STL的一个关联容器,map 容器中所有的元素都会根据元素对应的键值来排序,而键值key 是唯一值,并不会出现同样的键值key,也就是说假设已经有一个键值key 存在map 里,当同样的键值key 再insert 时,新的会覆盖掉旧的。
2、map内部所有的数据都是有序的。
3、multimap、unordered_map、map之间的区别:
map有序且键唯一,multimap有序且键可以不唯一,unordered_map是无序且键唯一。
二、map的操作
1、map的插入
最常见是数组方式。
#include <map> #include <string> #include <iostream> using namespace std; int main() { map<int, string> mapStudent; mapStudent[1] = "student_one"; mapStudent[2] = "student_two"; mapStudent[3] = "student_three"; map<int, string>::iterator it; for(it = mapStudent.begin(); it != mapStudent.end(); it++) { cout<<it->first<<" "<<it->second<<endl; } }
2、map的访问
map容器内元素的访问,通过下标进行访问。如:maps['c']=5;
通过迭代器进行访问,map可以使用it->first来访问键,使用it->second访问值。
#include<map> #include<iostream> using namespace std; int main() { map<char,int>maps; maps['d']=10; maps['e']=20; maps['a']=30; maps['b']=40; maps['c']=50; maps['r']=60; for(map<char,int>::iterator it=mp.begin();it!=mp.end();it++) { cout<<it->first<<" "<<it->second<<endl; } return 0; }
3、map的查找
按照关键字查找,相当于是索引------通过索引找到你想找的值。第一个存索引,第二个存值。
map的查找可以用find() 也可以用for循环 使用迭代器来查找。
用find函数来定位数据出现位置,它返回的一个迭代器,当数据出现时,它返回数据所在位置的迭代器,如果map中没有要查找的数据,它返回的迭代器等于end()函数返回的迭代器。
find(里面写的是索引----关键字),返回的是一个迭代器(类似指针)。
#include <map> #include <string> #include <iostream> using namespace std; int main() { map<int, string> mapStudent; mapStudent.insert(pair<int, string>(1, "student_one")); mapStudent.insert(pair<int, string>(2, "student_two")); mapStudent.insert(pair<int, string>(3, "student_three")); map<int, string>::iterator iter; iter = mapStudent.find(1); if(iter != mapStudent.end()) { cout<<"Find, the value is "<<iter->second<<endl; } else { cout<<"Do not Find"<<endl; } }
4、map的删除
#include <map>
#include <string> #include <iostream> using namespace std; int main() { map<int, string> mapStudent; mapStudent.insert(pair<int, string>(1, "student_one")); mapStudent.insert(pair<int, string>(2, "student_two")); mapStudent.insert(pair<int, string>(3, "student_three")); map<int, string>::iterator it; it = mapStudent.find(1); mapStudent.erase(it); //如果要删除1,用关键字删除 int n = mapStudent.erase(1);//如果删除了会返回1,否则返回0
//用迭代器,成片的删除 ,前闭后开。 mapStudent.earse(mapStudent.begin(), mapStudent.end()); }