stout代码分析之十一:hashmap和multihashmap
2024-10-21 09:44:50
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 = {{, "one"}, {, "two"}, {, "three"}};
- 其他api
- put, get
- contains, containsValue
- keys, values
示例代码如下:
#include "stout/hashmap.hpp"
#include <string>
#include <iostream> int main()
{
hashmap<int, std::string> a = {{, "one"}, {, "two"}, {, "three"}}; if (a.contains())
std::cout << "a contains 1" << std::endl; if (a.containsValue("one"))
std::cout << "a containsValue one" << std::endl; auto b = a.get();
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 ;
}
multihashmap是std::unordered_multimap的派生类,同样的,前者对后者的接口也进行了一些封装。
- 移动构造函数于hashmap相似
- initializer_list构造函数与hashmap相似
- api
- put, get, 注意get返回的是std::list类型
- keys
- remove,既可去除某个key对应的所有键值对,又可以去除指定的键值对.
- contains,既可判断某个key是否在该容器中,又可判断某对key-value是否在该容器中
最新文章
- 微信小程序开发调试工具
- linux虚拟系统determining IP information for eth0...failed
- CentOS 6.6安装Xtrabackup RPM提示缺少libev.so.4()
- tomcat跨域请求
- AngularJS $http
- ad组策略和sharepoint office打开文档关系
- C#对数组去重
- char 汉字
- 抓包分析TCP的三次握手和四次分手
- WPF 显示模态窗口和窗体
- linux shell获取时间
- div+css的叫法是不正确的
- PHP 之Mysql增删改查操作案例
- (转) xcodebuild和xcrun自动化编译ipa包 笔记
- Spring的事务属性
- HAOI2019+十二省联考 游记
- java.lang.IllegalAccessError: org.apache.commons.dbcp.DelegatingPreparedStatement.isClosed()Z
- AutoML技术现状与未来展望
- Doxygen的使用,配置及实例
- Java多线程-BlockingQueue-ArrayBlockingQueue-LinkedBlockingQueue