map映照容器
#include <iostream>
#include <map>
#include <string>
using namespace std;
//采用数据结构:红黑树 与set、multiset、multimap一样
//不允许插入重复键值
//map映照容器的元素由一个键值和一个映照数据一一对应组成
struct myCom //自定义比较函数
{
bool operator()( int a,int b)
{
//两种比较方法
// if(a!=b) return a>b;
// else return a>b;
return a>b;
}
};
struct Info
{
string name;
double score;
//重载<运算符 自定义排序规则
bool operator < (const Info &a) const
{
//按score从大到小排序 若从小到大 则用 >
return a.score < score;
}
};
int main()
{
//map创建、元素插入、遍历访问
map<string,float> m;
m["Tom"]=85.5;
m["Andy"]=95;
m["Jack"]=88;
map<string,float>::iterator it;
for(it=m.begin();it!=m.end();it++)
{
cout << (*it).first << ':' << (*it).second << endl;
}cout << endl;
//删除
m.erase("Tom");//删除键值为“Tom”的元素
for(it=m.begin();it!=m.end();it++)
{
cout << (*it).first << ':' << (*it).second << endl;
}cout << endl;
//反向遍历
map<int,char> a;
a[52]='s';
a[62]='d';
a[23]='c';
a[51]='b';
a[89]='n';
map<int,char>::iterator i;
for(i=a.begin();i!=a.end();i++)
{
cout << (*i).first << ' ' << (*i).second << endl;
}cout << endl;
map<int,char>::reverse_iterator j;//反向遍历
for(j=a.rbegin();j!=a.rend();j++) //注意是rbegin 和rend
{
cout << (*j).first << ':' << (*j).second << endl;
}cout << endl;
//搜索
i=a.find(52);//查找键值为52的元素
if(i!=a.end())//找到
{
cout << (*i).first << ':' << (*i).second << endl;
}
else //没找到
{
cout << "not find it! " << endl;
} cout << endl;
//自定义比较函数 (默认是从小到大)
map<int,int,myCom> z;
z[33]=45;
z[55]=52;
z[99]=83;
map<int,int,myCom>::iterator itt;
for(itt=z.begin();itt!=z.end();itt++)
{
cout << (*itt).first << ':' << (*itt).second << endl;
}cout << endl;
//若元素包含结构体
map<Info,int> x;
Info info;
info.name="Lucy" ;
info.score =96.5;
x[info]=1;
info.name="Candy" ;
info.score =66;
x[info]=2;
info.name="Sanfu" ;
info.score =89;
x[info]=3;
//使用前向迭代器中序遍历map
map<Info,int>::iterator y;
for(y=x.begin();y!=x.end();y++)
{
cout << (*y).second << ":";
cout << ((*y).first).name << ' ' << ((*y).first).score << endl;
} cout << endl;
//使用map实现数字分离 思想:把数字当成字符串,使用map一对一特性
map<char,int> mm;
//赋值:字符映照数字 :
mm['0']=0;
mm['1']=1;
mm['2']=2;
mm['3']=3;
mm['4']=4;
mm['5']=5;
mm['6']=6;
mm['7']=7;
mm['8']=8;
mm['9']=9;
//上述语句简写:
// for(int ii=0;ii<10;ii++)
// {
// mm['0'+ii]=ii;
// }
string sa,sb;
sa="1858"; //求各个位数字和
int jj,sum=0;
for(jj=0;jj<sa.length();jj++)
{
sum+=mm[ sa[jj] ];
} cout << "sum= " << sum << endl << endl;
//map 数字映照字符
map<int,char> c;
for(int q=0;q<10;q++)
{
c[q]='0'+q;
}
int n=7;
string ss="The Number Is: ";
cout << ss+c[n] << endl;
return 0;
}