最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c++ - Why can I pass a function return 64bit int as hasher? - Stack Overflow

programmeradmin4浏览0评论
#include <iostream>
#include <unordered_map>
#include <iterator>

using namespace std;
class point
{
public:
    float x, y;
    point() = default;
    point(float _x, float _y)
    {
        x = _x, y = _y;
    }
};
struct hash_point
{
    uint64_t operator()(const point& p) const
    {
        return uint64_t(p.x) + uint64_t(p.y);
    }
};

bool operator==(const point& p, const point& q)
{
    return p.x == q.x && p.y == q.y;
}
int main()
{
    point p = { 3.0f,3.0f };
    unordered_map<point, int, hash_point> m;
    cout << "size " << sizeof(size_t) << endl;
    cout << "size " << sizeof(m.hash_function()(p)) << endl;
    return 0;
}

The code above prints:

size 4 //I'm running this code under 32bits .
size 8 // strange ,hasher is supposed to return size_t type .

But I read from this webpage:

unordered map

Hash A unary function object type that takes an object of type key type as argument and returns a unique value of type size_t based on it. This can either be a class implementing a function call operator or a pointer to a function (see constructor for an example). This defaults to hash

So sizeof(m.hash_function()(p)) is supposed to return 4, isn't it ?

I compile this piece of code using visual studio 2022 .

发布评论

评论列表(0)

  1. 暂无评论