stout代码分析之十一:hashmap和multihashmap

  hashmap是std::unordered_map的子类,前者对后者的接口做了进一步封装。

  • hashmap的移动构造函数:
hashmap(std::map<Key, Value>&& map)
  {
    // NOTE: We're using 'insert' here with a move iterator in order
    // to avoid copies because we know we have an r-value paramater.
    std::unordered_map<Key, Value, Hash, Equal>::insert(
        std::make_move_iterator(map.begin()),
        std::make_move_iterator(map.end()));
  }

  std::make_move_iterator会将map.begin和map.end()转化为std::iterator类型,从而能够使用unordered_map::insert的右值语义。

  

  • hashmap从initializer_list构造
hashmap(std::initializer_list<std::pair<Key, Value>> list)
  {
    std::unordered_map<Key, Value, Hash, Equal>::reserve(list.size());

    for (auto iterator = list.begin(); iterator != list.end(); ++iterator) {
      std::unordered_map<Key, Value, Hash, Equal>::emplace(
          iterator->first,
          iterator->second);
    }
  }

  这样就可以直接初始化hash_map,如:

hashmap<int, std::string> a = {{1, "one"}, {2, "two"}, {3, "three"}};
  • 其他api
    • put, get
    • contains, containsValue
    • keys, values

  示例代码如下:

#include "stout/hashmap.hpp"
#include <string>
#include <iostream>

int main()
{
  hashmap<int, std::string> a = {{1, "one"}, {2, "two"}, {3, "three"}};

  if (a.contains(1))
    std::cout << "a contains 1" << std::endl;

  if (a.containsValue("one"))
    std::cout << "a containsValue one" << std::endl;

  auto b =  a.get(2);
  if (b.isSome())
    std::cout << "from a get " << b.get() << std::endl;

  auto c = a.keys();
  for (const int& x : c)
    std::cout << x << std::endl;
  
  auto d = a.values();
  for (const std::string& x : d)
    std::cout << x << std::endl;
  return 0;
}

 

  multihashmap是std::unordered_multimap的派生类,同样的,前者对后者的接口也进行了一些封装。

  • 移动构造函数于hashmap相似
  • initializer_list构造函数与hashmap相似
  • api
    • put, get, 注意get返回的是std::list类型
    • keys
    • remove,既可去除某个key对应的所有键值对,又可以去除指定的键值对.
    • contains,既可判断某个key是否在该容器中,又可判断某对key-value是否在该容器中

转载于:https://www.cnblogs.com/taiyang-li/p/5905097.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值