map映照容器

来源:互联网 发布:mac mysql dmg 安装 编辑:程序博客网 时间:2024/05/01 18:56

                       map映照容器

【map的定义】

map的头文件:#include<map>

定义:map<键值>数据;

【map的功能】

map中所有键值不允许重复。

map容器可应用于求一串字符中单词的数目(map<string,int>m),可用于存放学生对应的成绩(map<string,float>m)


注释:map的函数和之前的容器函数一样,可参考前面的set容器、vector容器的函数。

【map的基本操作】

1.创建、遍历、删除、插入。

#include<map>#include<string>#include<iostream>using namespace std;int main(){    map<string,float>m;    m["Jack"]=98.5;    m["Bomi"]=96.0;    m["Kate"]=97.5;    m["Make"]=96.6;    m["Anly"]=90.7;    // 前向遍历元素    map<string,float>::iterator it ;    for(it=m.begin();it!=m.end();it++)        cout<<(*it).first<<" : "<<(*it).second<<endl;    m.erase("Kate"); // 删除键值为“Kate”的元素    cout<<endl;    cout<<"New data"<<endl;    for(it=m.begin();it!=m.end();it++)    // (*it).first表示键值,(*it).second表示映照的数据        cout<<(*it).first<<" : "<<(*it).second<<endl;    // 反向遍历元素    cout<<endl;    cout<<"reverse data"<<endl;    map<string,float>::reverse_iterator rit;    for(rit=m.rbegin();rit!=m.rend();rit++)        cout<<(*rit).first<<" : "<<(*rit).second<<endl;    return 0;}
2.查找。

#include<map>#include<string>#include<iostream>using namespace std;int main(){    map<int,char>m;    m[25]='m';    m[28]='k';    m[60]='x';    m[85]='a';    m[100]='w';    m[41]='5';    m[88]='s';    m[90]='a';    map<int,char>::iterator it,x;    it=m.find(60);  // 查找键值为60的数据在迭代器的位置    /*if(it!=m.end())        cout<<(*it).first<<" : "<<(*it).second<<endl;    else        cout<<"not found it"<<endl;*/    cout<<"pass student"<<endl;    for(x=it;x!=m.end();x++)        // 输出键值为60以后的所有数据        cout<<(*x).first<<" : "<<(*x).second<<endl;    return 0;}
                                      multimap

multimap与map基本相同,唯独不同的是,multimap允许插入重复键值元素。

【multimap的基本操作】

1.插入、删除、查找

#include<map>#include<string>#include<iostream>#include <iomanip>using namespace std;int main(){    multimap<string,double>m;    // map 插入格式    m.insert(pair<string,double>("Jack",300.5));    m.insert(pair<string,double>("Kity",200));    m.insert(pair<string,double>("Memi",500));    m.insert(pair<string,double>("Jack",306));    m.insert(pair<string,double>("BOBO",521.1314));    multimap<string,double>::iterator it;    for(it=m.begin();it!=m.end();it++)        cout<<(*it).first<<" : "<<(*it).second<<endl;    // 删除键值等于“Jack"的元素    m.erase("Jack");    cout<<endl;    cout<<"the elements after deleted:"<<endl;    for(it=m.begin();it!=m.end();it++)        cout<<(*it).first<<" : "<<(*it).second<<endl;    // 查找键值为“BOBO”的元素    it=m.find("BOBO");    cout<<endl;    cout<<"the searching result"<<endl;    if(it!=m.end())<span style="white-space:pre"></span>// 如果查找到        cout<<(*it).first<<" : "<<(*it).second<<endl;    else<span style="white-space:pre"></span>// 查找不到        cout<<"not find it"<<endl;    return 0;}
扩展

           map容器由于是映照容器,所以可以处理很多两个数据有关联的操作。

           map以键值的排序,可以应用到对字符串处理的某些问题上。

0 0
原创粉丝点击