[英]Hashing function not working properly
我已經嘗試了一個星期,以了解如何使用std :: unordered_map和自定義哈希函數。 經過大量研究,我嘗試為glm :: ivec3實現自己的哈希函數。 我的問題是我遇到某種語法錯誤。 我沒有做錯什么,但這可能是我遺漏的東西。 這是我的標頭代碼:
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;
};
}
這是我的bug函數,需要從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:|
問題1
Chunk* result = chunks[ipos]; // Bug here
另外,在上述線你正在試圖分配chunks[ipos]
,它的類型的Chunk
,以result
其為類型的Chunk*
。
問題2
當調用std::unordered_map<...>::operator[]
(例如在chunks[ipos]
,除非已存在這樣的鍵,否則將默認構造 Key ( ipos
)上的值 。
換句話說,這種操作可能會更改使用它的容器。
由於您的成員函數 GetChunkFromPos被標記為const
您不允許修改類的任何成員,並且編譯器會向您拋出診斷信息-告訴您代碼格式錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.