You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

哈希映射值为哈希容器时,如何指定自定义哈希与相等函数?

为作为unordered_map值的自定义哈希容器指定哈希与相等函数

当你把带自定义哈希逻辑的unordered_set作为unordered_map的值类型时,核心要点是:外层unordered_map的构造参数只和自身的键哈希/相等逻辑有关,值容器的自定义参数属于unordered_set自身,不需要在map层面指定。具体实现方式如下:

1. 为自定义unordered_set起别名简化代码

由于unordered_set的类型声明包含哈希和相等函数的类型,写起来冗长,先定义别名:

// 基于已有的hashFunc和equalFunc定义自定义set类型
using MyCustomSet = std::unordered_set<
    std::pair<int, int>,
    decltype(hashFunc),
    decltype(equalFunc)
>;

2. 声明unordered_map并使用别名

直接用别名作为map的值类型即可,无需在map的构造中额外传递值容器的参数:

std::unordered_map<int, MyCustomSet> myMap;

3. 向map中插入自定义set实例

因为你用的lambda类型无法默认构造,所以每次创建MyCustomSet实例时,必须手动传入哈希和相等函数对象:

// 方式1:先构造set再插入
MyCustomSet tempSet(0, hashFunc, equalFunc);
tempSet.insert({1, 2});
myMap.emplace(100, std::move(tempSet)); // 用move避免不必要的拷贝

// 方式2:直接在emplace中构造set
myMap.emplace(
    200,
    MyCustomSet(0, hashFunc, equalFunc)
);

进阶:让自定义set支持默认构造(简化使用)

如果想直接用myMap[key]的语法自动创建符合要求的set,就不能用捕获外部变量的lambda,需要把哈希和相等逻辑改成可默认构造的函数对象结构体:

// 替换原lambda,改用结构体形式的函数对象
struct PairHash {
    size_t operator()(const std::pair<int, int>& p) const {
        // 此处编写你的自定义哈希逻辑,比如组合两个int的哈希值
        return std::hash<int>()(p.first) ^ (std::hash<int>()(p.second) << 1);
    }
};

struct PairEqual {
    bool operator()(const std::pair<int, int>& a, const std::pair<int, int>& b) const {
        return a.first == b.first && a.second == b.second;
    }
};

// 此时自定义set支持默认构造
using MyCustomSet = std::unordered_set<std::pair<int, int>, PairHash, PairEqual>;
std::unordered_map<int, MyCustomSet> myMap;

// 直接使用myMap[key],自动创建带有自定义逻辑的set
myMap[500].insert({3, 4});

内容的提问来源于stack exchange,提问作者PkDrew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 06:20:09