• 【C++ 学习笔记】:STLmultimap


    multimap提供了可以一种可以有重复键值的STL map类型。其插入方式和map相似,但是由于可以拥有重复键值所以在查找方面有些不同。

    查找

    1. 直接找到每种键值的所有元素的第一个元素的游标

    通过函数:lower_bound( const keytype& x ), upper_bound( const keytype& x ) 可以找到比指定键值x的小的键值的第一个元素和比指定键值x大的键值的第一个元素。返回值为该元素的游标。

    细节:当到达键值x已经是最大时,upper_bound返回的是这个multimap的end游标。同理,当键值x已经是最小了,lower_bound返回的是这个multimap的begin游标。

    2. 指定某个键值,进行遍历

    可以使用上面的lower_bound和upper_bound函数进行游历,也可以使用函数equal_range。其返回的是一个游标对。游标对pair::first是由函数lower_bound得到的x的前一个值,游标对pair::second的值是由函数upper_bound得到的x的后一个值。

    样例如下:

    multimap<int,int> a;
    a.insert(pair<int,int>(1,11));
    a.insert(pair<int,int>(1,12));
    a.insert(pair<int,int>(1,13));
    a.insert(pair<int,int>(2,21));
    a.insert(pair<int,int>(2,22));
    a.insert(pair<int,int>(3,31));
    a.insert(pair<int,int>(3,32));

    multimap
    <int,int>::iterator p_map;
    pair
    <multimap<int,int>::iterator, multimap<int,int>::iterator> ret;

    for(p_map = a.begin() ; p_map != a.end();)
    {
    cout
    <<p_map->first<<" =>";
    ret
    = a.equal_range(p_map->first);
    for(p_map = ret.first; p_map != ret.second; ++p_map)
    cout
    <<""<< (*p_map).second;
    cout
    <<endl;
    }

    结果:

    1 => 11 12 13
    2 => 21 22
    3 => 31 32



  • 相关阅读:
    8.【原创】使用Java8中的Stream特性筛选数据
    27.【转载】如何避免回表查询,什么是索引覆盖
    17.【转载】广东省2020学位英语考试报考须知
    Java 正则?:?=?!的理解
    集合的优化操作
    ArrayList中remove方法和set(null)的区别
    POI 导入、导出Excel
    JS 跳转到新页面并用post传参
    win 10 如何关闭自动更新
    JSON定义及应用
  • 原文地址:https://www.cnblogs.com/xiaoka/p/2132342.html
Copyright © 2020-2023  润新知