C++-STL(4)-unordered_set-自定义类型-实例源码

       自定义类型一般有三种实现方式,百度一下就出来了。目的都是重写hash 以及 equal
 其实都是三步走:
     1.自定义对象;
     2.重载operator;
     3,哈希函数 
 本文给出两种好用的,一个是struct的,一个是class的。照着做肯定可以用起来。
 本文的struct和class 成员变量都是基本数据类型,成员变量有自定义类型的参看
1.struct

struct Rect {
	int width;
	int height;
	string name;

public:
	Rect(int a, int b,string str)
	{
		width = a;
		height = b;
		name = str;
	}
	
};
//哈希函数
struct Rect_hash
{	
	size_t operator()(const Rect& r1) const
	{
		return hash()(r1.name) ^ hash()(r1.width) ^ hash()(r1.height);
	}
};
//equal相当于重载operator==
// int->string  to_string
//string temp = to_string(rc1.name) 
struct Rect_equal
{
	bool operator()(const Rect& rc1, const Rect& rc2) const noexcept
	{
		return rc1.width == rc2.width && rc1.height == rc2.height && rc1.name == rc2.name;
	}

};

void hashset_rect()
{
	unordered_set < Rect, Rect_hash, Rect_equal> rectS;
	rectS.insert({ 0,0,"rect0" });
	rectS.insert({ 1,1,"rect1" });
	rectS.insert({ 2,2,"rect2" });
	rectS.insert({ 3,3,"rect3" });
	for (auto it = rectS.begin(); it != rectS.end(); ++it)
	{
		cout << "name=" << it->name << ",width=" << it->width << ",heigh=" << it->height << endl;
	}
}


2.class
 

class Rect {
public:
	int width;
	int height;
	string name;


	Rect(int a, int b, string str)
	{
		width = a;
		height = b;
		name = str;
	}
	bool operator==(const Rect& rc) const
	{
		return name == rc.name && width == rc.width && height==rc.height;
	}

};

class Rect_hash
{
public:
	size_t operator()(const Rect& rc)const
	{
		return hash()(rc.name) ^ hash()(rc.width) ^ hash()(rc.height);
	}
	
};

void hashset_rect()
{
	cout<<"*******************"< rectS;
	rectS.insert(Rect(0, 0, "rect0"));
	rectS.insert(Rect(1, 1, "rect1"));
	rectS.insert(Rect(2, 2, "rect2"));
	rectS.insert(Rect(3, 3, "rect3"));
	
	for (auto it = rectS.begin(); it != rectS.end(); ++it)
	{
		cout << "name=" << it->name << ",width=" << it->width << ",heigh=" << it->height << endl;
	}
}

 

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