首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在指定散列函数时使用unordered_map<>中的默认存储桶计数

在指定散列函数时使用unordered_map<>中的默认存储桶计数
EN

Stack Overflow用户
提问于 2020-07-31 02:44:58
回答 1查看 257关注 0票数 4

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

有趣的是,Stroustrup C++第4版918页在没有使用桶大小的情况下构造了一个unordered_set<>,并且不同意文档中的构造函数参数。

代码语言:javascript
复制
explicit unordered_map ( size_type n = /* see below */,
                         const hasher& hf = hasher(),
                         const key_equal& eql = key_equal(),
                         const allocator_type& alloc = allocator_type() );

示例用法:

代码语言:javascript
复制
#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;
}
EN

回答 1

Stack Overflow用户

发布于 2020-07-31 03:22:18

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

代码语言:javascript
复制
#include <iostream>
#include <unordered_map>

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

这将在ideone中输出1

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63179462

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档