#include<map>
声明:map<type, type> mp;
表明从 key 到 value 的映射
什么时候用:
key是数字的时候用数组即可,在 key 不是数字,而是 character(也可用数组,而且更快)或string的时候考虑用map
或者key是数字,但是数字范围非常大,比如 0 ~ (1<<32) - 1 的时候用map进行离散化
Usage:
1,有重载 = 号,可以用 b=c; 这种方式赋值
2,插入数据,直接 map[key]=value
即可
3,clear content:mp.clear();
delete content:
it=mymap.find('b');
mymap.erase (it); // erasing by iterator
mymap.erase ('c'); // erasing by key
4,查找元素:mp.count(key);
返回值为bool型
mp.find(key);
返回值为 An iterator to the element, if an element with specified key is found, or map::end otherwise.( mp.end() )
app: iterator的用法:
map<type,type>::iterator it;
it->first //visit the key
it->second //visit the value
5, mp.size(); mp.empty();
6,遍历:
for(map<type,type>::iterator it=mp.begin(); it ! = mp.end(); ++it)
cout<<it->first<<' '<<it->second<<endl;
7,sort:
不能使用(也没必要使用),因为map中的值自动按照key的大小进行排序
map<char, int>mp;
for (int i = 0; i < 26; ++i)
mp[char(i + 'a') ] = 100-i;
for (map<char, int>::iterator it = mp.begin(); it != mp.end(); ++it)
cout << it->first << ' ';
运行结果:`a b c d e f g h i j k l m n o p q r s t u v w x y z`
Complexity:
插入和查找最坏情况都是对数
erase(pos) o(1); erase(val) o(logn) ;clear() : o(n)