C++ unordered_set 使用struct或者class

本文介绍如何将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 recordunordered_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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值