以HashTable为底层的容器(如unordered_map),在使用过程当中,必需要有一个hash function来为每个元素生成一个hash code做为元素在哈希表中的key,也就是元素在哈希表中的具体位置。对于一些build-in类型(好比字符串),标准库自带hash function,对于自定义类型来讲,这个函数该如何定义?咱们可否找到一个通用的方法,实现hash code的计算呢?算法
template<typename... Types> inline size_t hash_val(const Types&... args){ size_t seed = 0; hash_val(seed, args...); return seed; } template<typename T, typename... Types> inline void hash_val(size_t& seed, const T& val, const Type&... args){ hash_combine(seed, val); hash_val(seed, args...); } #include<functional> template<typename T> inline void hash_combine(size_t& seed, const T& val){ seed = std::hash<T>(val) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } //auxiliary generic funtions template<typename T> inline void hash_val(size_t& seed, const T& val){ hash_combine(seed, val); }
seed最终就被视为hash code数组
就是元组,实现了将不一样类型数据打包到一个数组中(其实就是Python中的touple)
实现:函数
type traits(类型萃取机)能有效地分辨类是否具备某种类型,经过调用它咱们能够实现对不一样的类型指定不一样的操做。ui
struct __true_type{}; struct __false_type{}; //泛化 template<class type> struct __type_traits{ typedef __true_type this_dummy_member_must_be_first; typedef __false_type has_trivial_default_constructor; typedef __false_type has_trivial_copy_constructor; typedef __false_type has_trivial_assignment_operator; typedef __false_type has_trivial_destructor; typedef __false_type is_POD_type; //POD = Plain Old Data,表明旧式的class 也就是struct }; //int的特化 template<> struct __type_traits<int>{ typedef __true_type has_trivial_default_constructor; typedef __true_type has_trivial_copy_constructor; typedef __true_type has_trivial_assignment_operator; typedef __true_type has_trivial_destructor; typedef __true_type is_POD_type; } //double的特化 template<> struct __type_traits<double>{ typedef __true_type has_trivial_default_constructor; typedef __true_type has_trivial_copy_constructor; typedef __true_type has_trivial_assignment_operator; typedef __true_type has_trivial_destructor; typedef __true_type is_POD_type; }
一个可移动的元素对STL算法有巨大的影响,不可移动的元素会进行深拷贝,容器中存储的是类的对象,则每次拷贝都要调用构造函数。而一个moveable对象在拷贝时能够拷贝指针,即浅拷贝。这效率是很是高的。this