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是否在该容器中
posted @ 2016-09-25 10:33  后端技术小屋  阅读(1340)  评论(0编辑  收藏  举报