自定义类型使用hash_map时自定义hash函数

#include <hash_map>
#include <string>
#include <iostream>

using namespace std;
//define the class
class ClassA{
        public:
        ClassA(int a):c_a(a){}
        int getvalue()const { return c_a;}
        void setvalue(int a){c_a;}
        private:
        int c_a;
};

//1 define the hash function
struct hash_A{
        size_t operator()(const class ClassA & A)const{
                //  return  hash<int>(classA.getvalue());
                return A.getvalue();
        }
};

//2 define the equal function
struct equal_A{
        bool operator()(const class ClassA & a1, const class ClassA & a2)const{
                return  a1.getvalue() == a2.getvalue();
        }
};


//可以在一个struct中同时定义两个函数

struct hash_string
{
 // 1. define the hash function
 size_t operator()(const string& str) const
 {
   unsigned long __h = 0;
   for (size_t i = 0 ; i < str.size() ; i ++)
    __h = 5*__h + str[i];
   return size_t(__h);
 }

 // 2. define the equal function
 bool operator()(const string& p1, const string& p2) const{
   return p1 == p2;
 }
};
int main()
{
    __gnu_cxx::hash_map<string, string, hash_string> strHMap;
    __gnu_cxx::hash_map<ClassA, string, hash_A, equal_A> hmap;

        ClassA a1(12);
        hmap[a1]="I am 12";
        ClassA a2(198877);
        hmap[a2]="I am 198877";
        
        strHMap["sss"] = "dddd";
        cout<<hmap[a1]<<endl;
        cout<<hmap[a2]<<endl;
        return 0;

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
unordered_map是一个C++标准库中的容器,用于存储键-值对,并且提供了快速的查找和插入操作。如果你想要使用自定义hash函数来定义unordered_map的键的哈希值,你可以通过提供一个自定义的哈希函数对象来实现。 举个例子,假设你有一个类叫做Customer,你想要使用自定义hash函数来计算它的哈希值。你可以创建一个自定义的哈希函数类,并重载其中的operator()函数来定义你的哈希函数。在这个函数中,你可以使用默认的哈希函数来计算每个成员变量的哈希值,然后将它们组合起来以生成最终的哈希值。 下面是一个示例代码: ```cpp class CustomerHash { public: std::size_t operator()(const Customer& c) const { std::size_t hashValue = 0; // 使用默认的哈希函数计算每个成员变量的哈希值 hashValue ^= std::hash<std::string>()(c.fname); hashValue ^= std::hash<std::string>()(c.lname); hashValue ^= std::hash<long>()(c.no); return hashValue; } }; // 创建一个使用自定义哈希函数的unordered_map std::unordered_map<Customer, std::string, CustomerHash> customerMap; ``` 在这个示例中,CustomerHash是一个自定义的哈希函数类,它重载了operator()函数来计算Customer对象的哈希值。在operator()函数中,我们使用了默认的哈希函数std::hash来计算每个成员变量的哈希值,并将它们进行异或操作以生成最终的哈希值。 通过将CustomerHash传递给unordered_map的第三个模板参数,我们告诉unordered_map使用自定义的哈希函数来计算键的哈希值。 请注意,为了正确使用自定义的哈希函数,你还需要定义一个等价准则,以确保在unordered_map中键的比较正确。你可以使用std::equal_to作为默认的等价准则,或者自定义一个等价准则类并传递给unordered_map的第四个模板参数。 希望这个例子能帮助你理解如何在unordered_map使用自定义的哈希函数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值