C++-STL(12)-unordered_set-自定义类型(2)key-自定义对象指针-实例源码

C++-STL(4)-unordered_set-自定义类型讲的自定义对象中的成员变量基础数据类型。
本篇实现的是成员变量自定义对象 key值自定义对象指针
注意点:1.创建:重载=,重载<, 哈希函数 
               2.删除时 要delete 和置空。

class nodeset {
public:
	int m_value;
	nodeset* next;

	nodeset(int val)
	{
		m_value = val;
		next = NULL;
	}
	bool operator==(const nodeset& rc) const       //重载=
	{
		return m_value == rc.m_value && next == rc.next;
	}
	bool operator < (const nodeset& n) const        //重载<
	{
		return m_value < n.m_value;
	}
		
	size_t operator()(const nodeset& rc)const                  //重载hash
	{
		return hash<int>()(rc.m_value) ^ hash<nodeset*>()(rc.next);
	}

};

void unorderset_node()
{
	cout << "*****unorderset_node*******************" << endl;
	cout << "新建*************" << endl;
	
	unordered_set <nodeset*> sp;
	nodeset* findnode = NULL;
	nodeset* deletenode = NULL;
	for (int i = 0; i < 5; i++)
	{
		nodeset* node = new nodeset(i);
		sp.insert(node);
		if (i == 2) { findnode = node; }
		if (i == 3) { deletenode = node; }
	}
	for (auto it = sp.begin(); it != sp.end(); ++it)
	{
		cout << "*iter=" << (*it)->m_value << endl;
	}


	unordered_set <nodeset*, int>::iterator it;
	for (it = sp.begin(); it != sp.end(); it++)
	{
		cout << "*iter=" << (*it)->m_value << endl;
	}
	cout << "查找 2*************" << endl;

	auto findit = sp.find(findnode);
	cout << "*findit=" << (*findit)->m_value << endl;
	cout << "删除 3 后*************" << endl;
	cout << "int n=" << sp.erase(deletenode) << endl;
	for (auto iter = sp.begin(); iter != sp.end(); ++iter)
	{
		cout << "*iter=" << (*iter)->m_value << endl;
	}
	
	cout << "释放*************" << endl;
	for (auto iter = sp.begin(); iter != sp.end(); )
	{
			delete *iter;				  // 释放指针
			iter = NULL;
			sp.erase(iter++);	         // 从map中删除元素,注意iter++的写法
		
	}
	sp.clear();
	cout <<"sp.size()" <<sp.size() << endl;  //此处为0
	for (it = sp.begin(); it != sp.end(); it++)
	{
		cout << "*iter=" << (*it)->m_value << endl;
	}

}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值