特点:①键值与映照数据一一对应
②插入的键值不允许重复
③比较函数只对元素的键值比较
④用法与set相似,红黑树(搜索速度极快)的数据结构
头文件:#include<map>//包含对multimap多重映照的定义
2.6.1 map创建、元素插入和遍历访问
2.6.2 删除元素 erase();clear();
2.6.3 元素反向遍历 rbegin();rend();
2.6.4 元素的搜索 find();end();
#pragma warning(disable:4786) #include <iostream> #include <string> #include <map> using namespace std; int main() { /* map<string,float> m; m["Jack"]=98.5; m["Bomi"]=96.0; m["Kate"]=97.5; map<string,float>::iterator it;//前向遍历元素 */ map<int,char> m;//键值由小到大放入黑白树中 m[25]='m'; m[28]='k'; m[10]='x'; m[30]='a'; /* m.erase(28);//删除键值为28的元素 */ map<int,char>::iterator it ;//前向遍历元素 it=m.find(28); if(it!=m.end())//搜索到该关键值 { cout<<(*it).first<<" : "<<(*it).second<<endl; } else { cout<<"not found it"<<endl; } /* for(it=m.begin();it!=m.end();it++) { //输出键值与映照数据 cout<<(*it).first<<" : "<<(*it).second<<endl; } map<int,char>::reverse_iterator rit;//反向遍历元素 for(rit=m.rbegin();rit!=m.rend();rit++) { cout<<(*rit).first<<" : "<<(*rit).second<<endl; } */ return 0; }
2.6.5 自定义比较函数
#pragma warning(disable:4786) #include <iostream> #include <string> #include <map> using namespace std; //自定义比较函数 struct myComp { bool operator() (const int &a,const int &b) { if(a!=b) return a>b; else return a>b; } }; //元素是结构体,比较函数写在结构体内 struct Info { string name; float score; bool operator < (const Info &a) const { return a.score<score; //按score由大到小排列 ,反之用> } }; int main() { /* map<int,char,myComp> m;//定义map对象,当前没有任何元素 m[25]='m';//插入元素,键值由小到大放入黑白树中 m[28]='k'; m[10]='x'; m[30]='a'; map<int,char,myComp>::iterator it;//使用前向迭代器中序遍历map for(it=m.begin();it!=m.end();it++) { cout<<(*it).first<<" : "<<(*it).second<<endl; } */ map<Info,int> m;//定义 map对象 Info info;//定义Info结构体变量 info.name="Jack";//插入元素,按键值的由小到大放入黑白树中 info.score=60; m[info]=25; info.name="Bomi"; info.score=80; m[info]=10; info.name="Peti"; info.score=66.5; m[info]=30; map<Info,int>::iterator it;//使用前向迭代器中序遍历map for(it=m.begin();it!=m.end();it++) { cout<<(*it).second<<" : "; cout<<((*it).first).name<<" "<<((*it).first).score<<endl; } return 0; }