unordered_set,unordered_map中自定义hashfunction

写在前面

在c++11新标准中引入了unordered_set以及unordered_map,其背后是根据hash实现,而set、map等背后是根据RB_tree实现,在实现hash时,需要将数据转换为对应的hash码,放入对应的bucket中,所以这里的hash function是至关重要的

简单的hash function

我们可以通过hash_function()函数得到对应的hash function函数

函数原型:

hasher hash_function() const;
	unordered_set str_set;
	unordered_set::hasher fn = str_set.hash_function();
//	auto fn = s.hash_function();    //使用auto自动推断函数类型即可 
	cout << "fn("<<"value"<<") = " << fn("value") << endl;

  

可以看到内部默认的hash function将string 类型的"value"转换为一个hash value

但是如果我们在unordered_set中存放自定义的结构体,就需要自己定义hash function

自定义hash function

先了解unordered_set中默认的模板内容

template < class Key,                        // unordered_set::key_type/value_type
           class Hash = hash,           // unordered_set::hasher
           class Pred = equal_to,       // unordered_set::key_equal
           class Alloc = allocator      // unordered_set::allocator_type
           > class unordered_set;

需要重写的函数包括hash 以及 equal_to

hash需要写成仿函数的形式,equal_to重载 == 操作符即可

#include 
#include 
#include 

using namespace std;

class Customer
{
public:
	Customer(string _name):id(num++),name(_name){
	}
	~Customer() = default; 
	friend ostream& operator<<(ostream& os,const Customer& a){
		os< s;
	s.insert({"张三"});
	s.insert({"赵四"});
	for_each(s.begin(),s.end(),[](const Customer& a){
		cout << a ;
	});
} 

参考资料

《c++11-14新标准》 侯捷

你可能感兴趣的:(C++深入)