本文介绍如何将unordered_set应用于strcut或者class
先看看其声明
template < class Key, // unordered_set::key_type/value_type
class Hash = hash<Key>, // unordered_set::hasher
class Pred = equal_to<Key>, // unordered_set::key_equal
class Alloc = allocator<Key> // unordered_set::allocator_type
> class unordered_set;
对于没有特殊需求的non-POD的int、string等类型来说,实用默认的模板参数即可,当我们要使用struct或者class等数据结构作为输入时,则需要一些特定的步骤。
假设我们需要为下面的结构体设置unordered_set容器:
struct record{
string num;
string file;
mutable int count;
record(string n,string f):num(n),file(f),count(1){}
};
1.指定hasher
将作为模板第二个参数
struct record_hash{
size_t operator()(const struct record& _r) const {
string tmp=_r.file+_r.num;
return std::hash<string>()(tmp);
}
};
2.指定符合hash函数的operator==
重载
bool operator==(const struct record & X,const struct record & Y)
{
return hash<string>()(X.num+X.file)==hash<string>()(Y.num+Y.file);
//or
//return (Y.num==X.num)&&(Y.file==X.file);
}
完成这两步之后,struct record
以unordered_set
为容器了:
struct record{
string num;
string file;
mutable int count;
record(string n,string f):num(n),file(f),count(1){}
};
bool operator==(const struct record & X,const struct record & Y)
{
//return hash<string>()(X.num+X.file)==hash<string>()(Y.num+Y.file);
return (Y.num==X.num)&&(Y.file==X.file);
}
struct record_hash{
size_t operator()(const struct record& _r) const {
string tmp=_r.file+_r.num;
return std::hash<string>()(tmp);
}
};
int main()
{
unordered_set<record,record_hash> records;
records.insert(record("zhang","xiao"));
record r("zhang","xiao");
auto it = records.find(r);
cout<<it->num<<" "<<it->file<<endl;
return 0;
}
参考
https://stackoverflow.com/questions/15869066/inserting-into-unordered-set-with-custom-hash-function
来源:CSDN
作者:NearXDU
链接:https://blog.csdn.net/zhangxiao93/article/details/73741460