map映照容器
1 //map映照容器是由一个键值和一个映照数据组成的,键值与映照数据之间具有一一映照的关系 2 //map映照容器的键值不允许重复 ,比较函数值对元素 3 //的键值进行比较,元素的各项数据可通过键值检索出来 4 5 6 #include<iostream> 7 #include<map> 8 #pragma warning(disable:4786) //强制编译器忽略标记符超长警告 9 #include<string> 10 using namespace std; 11 int main() 12 { 13 //定义map对象,当前没有任何元素 14 map<string,float> m1; 15 //插入元素,按键值的由小到大放入黑白数中 16 m1["Jack"]=98.5; 17 m1["Bomi"]=96.0; 18 m1["Kate"]=97.5; 19 //前向遍历元素 20 map<string,float>::iterator it; 21 for(it=m1.begin();it!=m1.end();it++) 22 { 23 //输出键值与映照数据 24 cout<<(*it).first<<":"<<(*it).second<<endl; 25 } 26 map<int,char> m2; 27 //插入元素,按键值的由小到大放入黑白树中 28 m2[25]='m'; 29 m2[28]='k'; 30 m2[10]='x'; 31 m2[30]='a'; 32 //删除键值为28的元素 33 m2.erase(28); 34 //前向遍历元素 35 for(map<int,char>::iterator it=m2.begin();it!=m2.end();it++) 36 { 37 //输出键值与映照数据 38 cout<<(*it).first<<":"<<(*it).second<<endl; 39 } 40 //可以使用反向迭代器reverse_iterator反向遍历map映照容器中的数据,需要rbegin()方法和rend()方法指出反向遍历的起始位置和终止位置 41 for(map<int,char>::reverse_iterator rit=m2.rbegin();rit!=m2.rend();rit++) 42 { 43 cout<<(*rit).first<<":"<<(*rit).second<<endl; 44 } 45 map<int,char>::iterator fit; 46 //使用find()方法来搜索某个键值,如果搜到了,返回其迭代器位置,否则,返回end()迭代器位置 47 fit=m2.find(25); 48 if(fit!=m2.end()) //搜索到该值 49 { 50 cout<<(*fit).first<<":"<<(*fit).second<<endl; 51 } 52 else 53 { 54 cout<<"not found it"<<endl; 55 } 56 //自定义比较函数myComp 57 /*struct myComp 58 { 59 bool operator()(const int &a,const int &b) 60 { 61 if(a!=b) return a>b; 62 else 63 return a>b; 64 } 65 }; 66 map<int,char,myComp> m3; 67 //插入元素,按键值的由大到小放入黑白树中 68 m3[25]='m'; 69 m3[28]='k'; 70 m3[10]='x'; 71 m3[30]='a'; 72 //使用前向迭代器中序遍历map 73 for(map<int,char,myComp>::iterator it1=m3.begin();it1!=m3.end();it1++); 74 { 75 cout<<(*it1).first<<":"<<(*it1).second<<endl; 76 } */ 77 //元素是结构体,可以直接把比较函数写在结构体内 78 /*struct Info 79 { 80 string name; 81 float score; 82 //重载"<"操作符,按score由大到小 83 bool operator<(const Info &a) const 84 { 85 return a.score<score; 86 } 87 }; 88 map<Info,int> m4; 89 //定义结构体变量 90 Info info; 91 info.name="Jack"; 92 info.score=60; 93 m[info]=25; 94 info.name="Bomi"; 95 info.score=80; 96 m[info]=10; 97 info.name="Peti"; 98 info.score=66.5; 99 m[info]=30; 100 map<Info,int>::iterator it2; 101 for(it2=m4.begin();it2!=m4.end();it2++) 102 { 103 cout<<(*it2).second<<":"; 104 cout<<((*it2).first).name<<((*it2).first.score<<endl; 105 }*/ 106 //用map实现数字分离采用取余方法操作耗时,把数字当字符串使用 map映照功能很方便实现了数字分离 107 map<char,int> m5; 108 m5['0']=0; 109 m5['1']=1; 110 m5['2']=2; 111 m5['3']=3; 112 m5['4']=4; 113 m5['5']=5; 114 m5['6']=6; 115 m5['7']=7; 116 m5['8']=8; 117 m5['9']=9; 118 /*上面的10条赋值语句也可采用下面这个循环来简化代码编写 119 for(int j=0;j<10;j++) 120 { 121 m['0'+j]=j; 122 }*/ 123 string sa,sb; 124 sa="6234"; 125 int i; 126 int sum=0; 127 for(i=0;i<sa.length();i++) 128 { 129 sum+=m5[sa[i]]; 130 } 131 cout<<"sum="<<sum<<endl; 132 //数字映照字符的map写法 133 map<int,char> m6; 134 for(int j=0;j<10;j++) 135 { 136 m6[j]='0'+j; 137 } 138 int n=7; 139 string s="The number is "; 140 cout<<s+m6[n]<<endl; 141 return 0; 142 }