map是关联容器,类似与数学中的映射,指的是两个元素之间的对应关系map中的元素是一些关键字—值(key—value)对,类似于python的‘字典’,关键字起到索引的作用,值则表示关键字相关联的数据。
map的定义
map<T1,T2> m;//定义了一个名为m的从T1类型指向T2类型映射,初始为空插入映射
用insert()方法插入一个元素或一个元素范围,参数是pair类型(元组),我们向映射中加入新的映射的时候就是通过加入pair来实现的,如果插入的key已经有了对应的value,则此次插入无效,而如果想让关键字重复出现的话,可以用multmap。
#include<iostream> #include<map> using namespace std; int main() { map<string,int> m; string fruits; int amount; cin >> fruits >> amount; m.insert(pair<string,int>(fruits,amount)); m.insert(pair<string,int>("apple",5)); return 0; }访问映射
和数组一样,直接用[]就能访问。比如m["apple"]就可以知道苹果的数量。
#include<iostream> #include<map> using namespace std; int main(){ map<string,int> m; m.["apple"] = 3; m.["banana"] = 1; cout << m["apple"] << endl; cout << m["banana"] << endl; return 0; }有一种更便捷的插入手段:如果没有对“apple”做过映射的话,此时你访问m["apple"]系统会自动为"apple"生成一个映射,气value为对应类型的默认值。我们可以再给映射赋新的值,如下
查找关键字
m.find(k);//返回一个迭代器,指向第一个关键字为k的元素,若k不存在容器中,则返回尾后迭代器m.count(k);//返回关键字等于看的元素的数量,对于不润徐重复关键字的容器,返回值永远是0或1m.lower_bound(k);//返回一个迭代器,只想第一个关键字不小于k的元素m.upper_bound(k);m.equal_range(k);//返回一个迭代器pair,表示关键字等于k的元素的范围 #include<iostream> #include<map> using namespace std; int main() { map<string,int> m; string fruits; int amount; m["apple"] = 7; m["banana"] = 5; m["orange"] = 3; if(m.count("apple")){ cout<<"We have " << m["apple"]<<" apples"<<endl; } return 0; }
遍历映射
#include<iostream> #include<map> using namespace std; int main() { map<string,int> m; string fruits; int amount; m["apple"] = 7; m["banana"] = 5; m["orange"] = 3; for(map<string,int>::iterator it = m.begin(); it != m.end(); it++){ cout<< it->first<< " "<< it->second<< endl; } return 0; }当从map中提取一个元素时,会得到一个pair类型的对象,pair是一个模板,保存两个名字为first和second的数据成员,pair用first成员保存关键字,second保存对应的值
删除元素
查找关键字可以使用count()方法在map中查找关键字,找到返回 1,否则返回 0
#include<iostream> #include<map> using namespace std; int main() { map<string,int> m; string fruits; int amount; m["apple"] = 7; m["banana"] = 5; m["orange"] = 3; if(m.erase("apple")) cout<<"apple removed" <<endl; for(map<string,int>::iterator it = m.begin(); it != m.end(); it++){ cout<< it->first<< " "<< it->second<< endl; } return 0; }对于不重复容器,earse()的返回值总是0或1,若erase()的返回值为0,则表示想要删除的元素不在容器中,
对于重复容器,earae()返回值可能大于1
清空
调用clear()方法清空map
查找关键字可以使用count()方法在map中查找关键字,找到返回 1,否则返回 0