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

       自定义类型一般有三种实现方式,百度一下就出来了。目的都是重写hash<Key> 以及 equal<Key>。
 其实都是三步走:
     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<string>()(r1.name) ^ hash<int>()(r1.width) ^ hash<int>()(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<string>()(rc.name) ^ hash<int>()(rc.width) ^ hash<int>()(rc.height);
	}
	
};

void hashset_rect()
{
	cout<<"*******************"<<endl;
	unordered_set < Rect, Rect_hash> 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;
	}
}

 

  • 15
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值