在ACM中常用的指令。
map是STL内的一个关联容器,提供一对一的映射,每个关键字(key)在容器中只出现一次,然后提供一个对应的值(value).
1.初始化
map<int,string> m;
2.插入元素
m[1]=”what”,m[2]=”the”//map中最常用的插入添加
使用pair插入
Employees.insert(std::pair<string, int>("aaa", 110));
Employees.insert(map<string, int>::value_type("bbb", 111));
Employees.insert(make_pair("ccc", 112));
3.[]访问
string s = m[1]; //使用前先用find或者count来判断map中是否含有关键值1
4.find查找
find()函数返回一个迭代器指向键值为key的元素,如果没找到就返回指向map尾部的迭代器。
map::iterator it;;
it=m.find(110);
if(it==m.end())
cout<<"not find 110"<<endl;
else cout<<"we find 110"<<endl;
5.map中元素的删除:
如果删除110;
map::iterator it;;
it=m.find(110);
if(it==m.end())
cout<<"not find 110"<<endl;
else m.erase(it); //delete 110;
6.map的sort排序问题
Map中的元素是自动按key升序排序,所以不能对map用sort函数。
7.map中swap的用法
map<int,int>m1;map<int,int>m2;
m1.swap(m2);
Map中的swap不是一个容器中的元素交换,而是两个容器交换;交换两个map的内容。map的底层实现保证swap是非常有效率的,几乎是常数时间。(通常只需要交换两个指针的值)。值得注意的是,两个map的模板类型必须是一样,否则会出错。
8.map基本操作函数
begin() 返回指向map头部的迭代器
clear() 删除所有元素
count() 返回指定元素出现的次数
empty() 如果map为空则返回true
end() 返回指向map末尾的迭代器
erase() 删除一个元素
find() 查找一个元素
insert() 插入元素
lower_bound() 返回键值>=给定元素的第一个位置
max_size() 返回可以容纳的最大元素个数
rbegin() 返回一个指向map尾部的逆向迭代器
rend() 返回一个指向map头部的逆向迭代器
size() 返回map中元素的个数
swap() 交换两个map
upper_bound() 返回键值>给定元素的第一个位置
value_comp() 返回比较元素value的函数