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;
}
}