c++ - 哈希函数无法正常工作

标签 c++ opengl hash std

为了了解如何使用 std::unordered_map 和自定义哈希函数,我已经尝试了一个星期。经过大量研究,我尝试为 glm::ivec3 实现自己的哈希函数。我的问题是我有某种语法错误。我不知道我做错了什么,但这可能是我遗漏的。这是我的 header 代码:

namespace mctest3
{
    class ChunkMap
    {
    public:
        struct KeyHasher
        {
            std::size_t operator()(const glm::ivec3& key) const
            {
                using std::size_t;
                using std::hash;

                return ((key.x * 5209) ^ (key.y * 1811)) ^ (key.z * 7297);
            }
        };


        std::unordered_map<glm::ivec3, Chunk, KeyHasher> chunks;

        ChunkMap();

        Chunk* GetChunkFromPos(const glm::vec3 &pos) const;
        glm::ivec3 GetChunkPosFromPos(const glm::vec3 &pos) const;
    };
}

这是我的错误函数,我需要从我的 unordered_map 中检索一个值(或创建一个值):

namespace mctest3
{
    ChunkMap::ChunkMap()
    {
    }

    Chunk* ChunkMap::GetChunkFromPos(const glm::vec3 &pos) const
    {
        glm::ivec3 ipos = glm::ivec3((int)pos.x >> Chunk::BIT_SIZE, (int)pos.y >> Chunk::BIT_SIZE, (int)pos.z >> Chunk::BIT_SIZE);
        Chunk* result = chunks[ipos]; // Bug here
        return result;
    }
}

这是我得到的两个错误:

ChunkMap.cpp|12|error: passing 'const std::unordered_map<glm::detail::tvec3<int, (glm::precision)0u>, mctest3::Chunk, mctest3::ChunkMap::KeyHasher>' as 'this' argument of 'std::__detail::_Map_base<_Key, _Pair, std::_Select1st<_Pair>, true, _Hashtable>::mapped_type& std::__detail::_Map_base<_Key, _Pair, std::_Select1st<_Pair>, true, _Hashtable>::operator[](const _Key&) [with _Key = glm::detail::tvec3<int, (glm::precision)0u>; _Pair = std::pair<const glm::detail::tvec3<int, (glm::precision)0u>, mctest3::Chunk>; _Hashtable =|

ChunkMap.cpp|12|error: cannot convert 'std::__detail::_Map_base<glm::detail::tvec3<int, (glm::precision)0u>, std::pair<const glm::detail::tvec3<int, (glm::precision)0u>, mctest3::Chunk>, std::_Select1st<std::pair<const glm::detail::tvec3<int, (glm::precision)0u>, mctest3::Chunk> >, true, std::_Hashtable<glm::detail::tvec3<int, (glm::precision)0u>, std::pair<const glm::detail::tvec3<int, (glm::precision)0u>, mctest3::Chunk>, std::allocator<std::pair<const glm::detail::tvec3<int, (glm::precision)0u>, mctest3::Chunk> >, std:|

最佳答案

问题一

Chunk* result = chunks[ipos]; // Bug here

在上面的行中,您试图分配 chunks[ipos] , 类型为 Chunkresult这是类型 Chunk* .


问题2

调用std::unordered_map<...>::operator[]时,例如 chunks[ipos] ( ipos ) 处的值将默认构造,除非已经存在这样的键。

换句话说,这样的操作可能改变使用它的容器。

由于您的成员函数 GetChunkFromPos 被标记为 const您不得修改您的类的任何成员,并且编译器会向您抛出诊断信息 - 告诉您代码格式错误。

关于c++ - 哈希函数无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24003071/

相关文章:

c++ - 打开 C++ 崩溃转储不会在调用堆栈中显示正确的行

c++ - 由于类型不匹配,无法将一个指针分配给另一个指针,或者编译器这样说

C++ Win32 如何创建一个 "toggle"按钮

c++ - 如何加快在 OpenGL 中绘制纹理的速度? (3.3+/4.1)

language-agnostic - CPU 或 GPU 绑定(bind)?分析 OpenGL 应用程序

visual-studio - 在 Visual C++ Express Edition 中使用 GLUT

c++ - 如何在 Qt 中使用 QDataStream 将自定义结构保存/加载到二进制文件中?

java - 使用对象或整数作为 HashMap 键更好吗?

algorithm - 在散列算法之上使用另一种算法

Scala 单线从字符串生成 MD5 哈希