zoukankan      html  css  js  c++  java
  • STL-map and multimap

    定义
    map<int,int> a;
    map<int,string> a;
    map<double,int> a;
    ……
    首先要知道的一些
    Map是STL的一个关联容器,它提供一对一的数据处理能力,map不允许重复元素。
    
    其中第一个称为关键字key,每个关键字只能在map中出现一次,第二个称为该关键字的值value,元素的次序由它们的key决定,和value无关。
    
    Map 中的元素总是保持单调递增。
    begin() 返回的迭代 器指向map 中的最小key值;
    rbegin() 返回的迭代器指向 map 中的最大key值。
    end() 返回的迭代 器指向 Map 中的最后元素的后一个位置;
    rend() 返回指向Map中第一个元素的反向迭代器
    赋值
    map<int,int> a;
    //方法一:用insert函数插入pair数据
    a.insert(make_pair(1,1));
    //方法二:数组覆盖
    a[1]=1;
    
    /*需要注意的是:
       用insert函数插入数据,在数据的插入上涉及到map关键字的唯一性这个概念。即当map中有这个关键字时,insert操作无效的。
       用数组方式它可以覆盖以前该关键字对应的值*/
    遍历

    要输出所有元素需要使用迭代器依次遍历

    map<int,int> a;
    
    map<int,int>:: iterator i;
    for(i=a.begin();i!=a.end();i++)
    printf("%d %d
    ",i->first,i->second);

    map的反序遍历参照set和vector

    函数
    size(),empty(),clear() 不多加赘述
    
    count() 用来查找Map中某个某个键值出现的次数,这个函数在Map只可能出现0或1次。
    
    find(x) 返回x元素的迭代器,如果找不到x就返回 end()的迭代器。
    若有多个key值对应的value为x 则会返回key值最小的那个迭代器
    
    lower_bound(x) 返回map中key大于等于x的最小元素的迭代器。 
    
    upper_bound(x) 返回map中key大于x的最小元素的迭代器。如果找不到也会返回end()的迭代器。
    
    erase(x):
    其中x可以是具体的数或迭代器。删除map中不存在的元素会被忽略。
    a.erase(a.begin(),a.end())效果和a.clear()相同
      //find参考程序
      a.insert(make_pair(2,1));
      a.insert(make_pair(1,1));
      map<int,int>:: iterator i;

    multimap

    与map的区别
      !它允许重复键。即一个关键词可以有很多不同的值。这些值按插入的时间顺序排列。
    
      插入:在multimap中没有定义[]运算符,因此,multimap进行插入的时候,只能利用insert()函数进行插入。
    
      查找:使用find(x)查找返回每种关键词的所有元素的第一个元素的迭代器。
    
    
    指定关键字的遍历
    1. equal_range(x)
    返回一对iterator的pair,表示关键词x的位置的区间(左闭右开)。 
    
    2.可用lower_bound与upper_bound实现
    multimap<int,int> a;
    #define it multimap<int,int>:: iterator
    
      a.insert(make_pair(2,3));
      a.insert(make_pair(2,1));
      a.insert(make_pair(2,4));
      a.insert(make_pair(7,1));
      a.insert(make_pair(8,1));
    
     //equal_range()
    
      pair<it,it> r=a.equal_range(2);
      for(it i=r.first;i!=r.second;i++)
        cout<<i->first<<" "<<i->second<<endl;
    
     //lower_bound and upper_bound
    
      for(it i=a.lower_bound(2);i!=a.upper_bound(2);i++)
      cout<<i->first<<" "<<i->second<<endl;
    光伴随的阴影
  • 相关阅读:
    asp.net c#中FCKeditor的详细配置及精简操作
    winform C#中Byte与String的转换方法,相互转换
    wp,wordpress博客怎样让首页的文章默认显示摘要
    vs2005 c#鼠标悬停高亮显示在gridview中
    我国CN域名一年减少600万个 全要求实名注册
    c# winform未能找到引用的组件“Excel”的解决办法
    asp.net c#中使用FCKeditor的方法,版本2.66
    C# 注册表操作类(完整版)winform
    c#如何打印picturebox里的图片,winform怎样打印picturebox里的图片
    imageready 如何保存为gif格式图片总结.
  • 原文地址:https://www.cnblogs.com/forward777/p/10087058.html
Copyright © 2011-2022 走看看