ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

c – 使用unordered_multimap播放

2019-08-25 16:08:05  阅读:196  来源: 互联网

标签:unordered-map c c11 hashmap


所以,伙计们,我正在玩std :: unordered multimap只是为了好玩.我想存储(在这个例子中)unsigned short,带有自定义哈希并且相等.

有趣的是什么?如果它们是偶数或奇数,则两个项目相等.

所以,据我所知,我不能使用std :: unordered_map,即使实际值不同:自定义谓词另有说法. (如果我错了,请纠正我,显然!)

所以回顾一下:我存储了不同的整数,因此存储了不同的哈希值,但它们在谓词下的值可能是相同的.

#include <iostream>
#include <unordered_map>

class tt
{
public:

    tt(const unsigned short v = 0) : i(v) { };

    unsigned short i;
};

class tt_hash
{
public:
    size_t operator()(const tt &v) const
    {
        auto f = std::hash<unsigned short>();
        return f(v.i);
    };
};

class tt_equal
{
public:
    bool operator()(const tt &u, const tt &v) const
    {
        return (u.i % 2) == (v.i % 2);
    };
};

typedef std::unordered_multimap<tt, bool, tt_hash, tt_equal> mymap;

// Print all values that match a criteria
void f(const mymap &m, unsigned short c)
{
    auto range = m.equal_range(c);

    auto target = range.first;

    if (target == m.end())
    {
        std::cout << "not found : " << (int) c << std::endl;
    }
    else
    {
        for (auto i = target; i != range.second; i++)
            std::cout << "there is  : " << (int) i->first.i << " : " << i->second << std::endl;
    }

}

int main(int argc, const char * argv[])
{    
    mymap m;

    m.emplace(std::make_pair(tt(3), false));
    m.emplace(std::make_pair(tt(10), true));
    m.emplace(std::make_pair(tt(4), true));
    m.emplace(std::make_pair(tt(23), false));

    std::cout << "size " << m.size() << std::endl;
    std::cout << "buck " << m.bucket_count() << std::endl;

    int c = 0;

    for (auto i = m.begin(); i != m.end(); i++)
        std::cout << "# " << c++ << " : " << (int) i->first.i << " : " << i->second << std::endl;

    f(m, 3);

    return 0;
}

所以,当我执行上面的代码时,我找到了正确的值,3,10,4,23(当然不是按此顺序).

出乎意料的是,当打印所有匹配3调用f()的值时,我得到两个答案,3和23;但是当我要求1000时,我希望打印所有偶数,但我错了:

size 4
buck 5
# 0 : 4 : 1
# 1 : 10 : 1
# 2 : 3 : 0
# 3 : 23 : 0
there is  : 10 : 1

我在这里错过了什么吗? (答案显然是肯定的)

解决方法:

你正在做的是未定义的行为:相等的元素应具有相等的哈希值.根据标准(强调我的)

23.2.5无序关联容器[unord.req]

5 Two values k1 and k2 of type Key are considered equivalent if the
container’s key equality predicate returns true when passed those
values. If k1 and k2 are equivalent, the container’s hash function
shall return the same value for both
.

由于您使用模2定义了等价,因此您还需要在传递的整数的模2上使用散列函数.这也意味着只要有2个以上的元素,就需要std :: unordered_multimap.

标签:unordered-map,c,c11,hashmap
来源: https://codeday.me/bug/20190825/1720587.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有