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;
    光伴随的阴影
  • 相关阅读:
    获取Windows DPI
    你的float用对了吗
    Overhead of a .NET array
    【原】灵活运用sessionStorage或者localStorage
    【总结】总结写了3个React页面后遇到的各种坑
    【学】AngularJS日记(4)- 过滤器的使用
    【学】AngularJS日记(3)- $apply(), run()方法
    【学】AngularJS日记(2)
    【学】AngularJS日记(1)
    【学】React的学习之旅7-官方例子总结
  • 原文地址:https://www.cnblogs.com/forward777/p/10087058.html
Copyright © 2011-2022 走看看