指定哈希函数时,在 unordered_map<> 中使用默认存储桶计数

not*_*orb 6 c++ templates 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() );
Run Code Online (Sandbox Code Playgroud)

用法示例:

#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;
}
Run Code Online (Sandbox Code Playgroud)

and*_*dre 3

看起来我们可以访问该bucket_count值。我只需在您的环境中运行以下代码并检查它为您提供的值。

#include <iostream>
#include <unordered_map>

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

1这在 ideone 中输出