zoukankan      html  css  js  c++  java
  • C++ 之关联容器 map

    标准库定义了四种关联容器:map是其中之一(另外还有set、multimap、multiset)。map的元素以键-值(key-value),在学了顺序容器之后,再学习关联容器,就比较比较好理解了。

    map类型,可以说是键-值对的集合,每一个键都与一个或多个值相关联。

    利用它可以构造多钟函数:

    map<string , int >   a;

    map<char ,int>   b; 

    map<srting ,char >  c;

    map<int,vector<int> > d;       等等

    关于使用map函数的一些基本操作,不想用文字去多废话,直接看程序吧;

    有关   插入数据   使用迭代器   查找    删除   获取长度     的基本操作:

     1 #include<iostream>
     2 #include<map>
     3 using namespace std;
     4 int main(){
     5     map<int,int> m;
     6    //定义迭代器
     7     map<int,int>::iterator  mIter; 
     8     //插入数据方法1
     9     m.insert(pair<int,int> (1,20) );
    10     m.insert(pair<int,int> (4,20) );
    11     m.insert(pair<int,int> (5,20) );
    12     //法2
    13     m.insert(map<int,int>::value_type (7,6) );
    14     //法3  类似数组
    15     m[8]=9;
    16     
    17     //查找与清除,均是利用到健值
    18     map<int,int>::iterator  a = m.find(1);
    19     if(a!=m.end()){
    20         m.erase(a);
    21     }
    22     for(mIter = m.begin();mIter!=m.end();mIter++)
    23         cout<<mIter->first<<" "<<mIter->second<<endl;
    24     //获取长度
    25     cout<<m.size()<<endl;
    26     return 0;
    27 }

    值得注意一点,关联容器会自己帮你排序,排序是根据key(键)的大小,这一点它比顺序容器要好用用一些,还有就是因为这个原因,你map里面所定义的key(键)一定是要可以比较大小的类型。

    修改

     1 #include<iostream>
     2 #include<map>
     3 #include<string>
     4 using namespace std;
     5 int main(){  
     6     map<char ,string>  n;
     7     map<char ,string>::iterator it;
     8     map<char ,string>::value_type   num1('1',"xioaming");
     9     n.insert(num1);
    10     n['2'] = "xiaoli";
    11     //遍历修改,虽说只有俩元素
    12     for(it=n.begin();it!=n.end();it++)
    13     {
    14             it->second="xiaoqiu";
    15             cout<<it->first<<endl;
    16                 cout<<it->second<<endl;
    17     }
    18             return 0;
    19 }

    最后在加上一个书本上的一个计算单词个数的程序

     1 #include <iostream>
     2 #include <map>
     3 #include <string>
     4 using namespace std;
     5 int main()
     6 {
     7     string s;
     8     map<string, int> counters;    
     9     while (cin >> s)   // 读取单词并且计数
    10         ++counters[s];
    11     for (map<string, int>::const_iterator it = counters.begin();it != counters.end(); ++it) {
    12         cout << it->first << "	" << it->second << endl;
    13     }
    14     return 0;
    15 }
  • 相关阅读:
    60.django session缓存配置
    Jmeter学习笔记-Jmeter目录文件
    Jmeter用户手册目录
    Jmeter学习笔记-jmeter执行结束报错:The JVM should have exitted but did not
    PPT-分割图片
    bug记录-权限问题,比如说默认搜索条件为子系统,则在该子系统下面的接口模版,在搜索条件下也应该有权限的限制
    bug记录-弹出框,刚配置的时候记录少,当记录过多时,容易出现高度过高,所以要对高度进行限制,以及设置滚动条
    Jmeter学习笔记-20181224安装软件路径及linux安装方法
    bug记录-列表头部缺失,点开页面,列表头部存在,然后点击搜索后,某个枚举没有值,搜出来没有列表头部,换成其他有值的列表头部,列表头部不显示了
    视频录制与剪辑备忘记录
  • 原文地址:https://www.cnblogs.com/LZYY/p/3242632.html
Copyright © 2011-2022 走看看