一、时间复杂度
O(logn)
二、优点
可使用键作为下标来获取一个值。请注意:关联的本质在于元素的值与某个特定的键相关联,而并非通过元素在数组中的位置来获取。
三、头文件
#include<map>
四、操作方法
map<int,string> map1; //默认为空
map<string,int> mp ;
mp["hello"] = 8 ;
mp["hello"] = 100 ;
mp["aloha"] = 666 ;
mp["good"] = 777 ;
for(map<string,int>::iterator it=mp.begin();it!=mp.end();it++){
cout << it->first << ' ' << it->second << endl ;
}
输出结果:aloha 666
good 777
hello 100
-
常用函数
(1)find(key):返回键为key的映射的迭代器
map<string,int> mp ; mp["hello"] = 8 ; mp["hello"] = 100 ; mp["aloha"] = 666 ; mp["good"] = 777 ; map<string,int>::iterator it = mp.find("good") ; cout << it->first << ' ' << it->second << endl ; 输出结果:good 777
(2)erase():删除单个元素和删除一个区间内的元素。
map<string,int> mp ; mp["hello"] = 8 ; mp["hello"] = 100 ; mp["aloha"] = 666 ; mp["good"] = 777 ; mp.erase(mp.find("good"));//也可以直接像这样写一个键mp.erase("good"); map<string,int>::iterator it = mp.begin(); for(;it!=mp.end();it++) cout << it.first << ' ' << it.second << endl ; //删除一个区间的元素,这里只能用迭代器删除,erase(st,ed),表示删除[st,ed)区间内的元素。 map<string,int> mp ; mp["hello"] = 8 ; mp["hello"] = 100 ; mp["aloha"] = 666 ; mp["good"] = 777 ; mp.erase(mp.find("good"),mp.find("hello")); for(auto ele : mp){//写成iterator迭代器就可以 cout << ele.first << ' ' << ele.second << endl ; } 输出结果:aloha 666 hello 100
(3)size():用来获得map中映射的对数,时间复杂度O(1)。
map<string,int> mp ; mp["hello"] = 8 ; mp["hello"] = 100 ; mp["aloha"] = 666 ; mp["good"] = 777 ; cout << mp.size() << endl ; 输出结果:3
(4)clear():用来清空map中所有元素,复杂度为O(N),其中N为map中元素的个数。
map<string,int> mp ; mp["hello"] = 8 ; mp["hello"] = 100 ; mp["aloha"] = 666 ; mp["good"] = 777 ; mp.clear() ; cout << mp.size() << endl ; 输出结果:0