首页 > 解决方案 > 指定哈希函数时在 unordered_map<> 中使用默认存储桶计数

问题描述

我正在使用 unordered_map<> 并且很好奇,在将哈希函数指定为第二个参数(下面的每个代码)时,size_type n必须将存储桶计数指定为构造函数中的第一个参数。我已阅读应使用默认存储桶计数。有谁知道在使用自己的哈希函数时如何使用默认的桶计数参数?

有趣的是,Stroustrup C++ 第 4 版第 918 页构造了一个 unordered_set<> 而不使用桶大小,并且不同意记录的构造函数参数。

explicit unordered_map ( size_type n = /* see below */,
                         const hasher& hf = hasher(),
                         const key_equal& eql = key_equal(),
                         const allocator_type& alloc = allocator_type() );

示例用法:

#include <unordered_map>
#include <functional>
#include <iostream>
using namespace std;

struct X {
    X(string n) : name{n} {}
    string name;
    bool operator==(const X& b0) const { return name == b0.name; }
};

namespace std {
    template<>
    struct hash<X> {
        size_t operator()(const X&) const;
    };
    size_t hash<X>::operator()(const X& a) const
    {
        cout << a.name << endl;
        return hash<string>{}(a.name);
    }
}

size_t hashX(const X& a)
{
    return hash<string>{}(a.name);
}

int main()
{
//    unordered_map<X,int,hash<X>> m(100, hash<X>{});
//    unordered_map<X,int,function<size_t(const X&)>> m(100, &hashX);
    unordered_map<X,int,size_t(*)(const X&)> m(100, &hashX);
    X x{"abc"};
    m[x] = 1;
    int i = m[x];
    cout << i << endl;
}

标签: c++templatesunordered-map

解决方案


似乎我们可以访问该bucket_count值。我将在您的环境中运行以下代码并检查它为您提供的值。

#include <iostream>
#include <unordered_map>

int main() {
    std::unordered_map<int, int> m;
    std::cout << m.bucket_count() << std::endl;
    return 0;
}

1在ideone中输出


推荐阅读