以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