指向unordered_map表项的指针改变了,但表项不变

C++ Pointer to unordered_map entry changes, but entry not

本文关键字:改变 unordered map 指向 指针      更新时间:2023-10-16

我试图通过使用指向该条目的指针调用函数来设置unordered_map条目"chunk"的变量。指针改变了它的值"chunkIndex",但映射项不是

glm::ivec3 chunkIndex(1, 1, 1);
chunks.insert(make_pair(chunkIndex, Chunk()));
chunk = &chunks[chunkIndex];
chunk->setChunkIndex(chunkIndex);
logVector(chunk->chunkIndex);                      // output: 1, 1, 1
logVector(chunks[chunk->chunkIndex].chunkIndex);   // output: 0, 0, 0

"chunks"是类型为:

的unordered_map
typedef unordered_map<glm::ivec3, Chunk, KeyHash, KeyEqual> ChunkMap;

你知道为什么只有指针改变它的值,而不是被引用的对象吗?

提前感谢!

更新:

chunks.insert(make_pair(chunkIndex, Chunk()));
log((chunks.find(chunkIndex) == chunks.end()) ? "true" : "false");

这段代码输出true,所以如果插入的条目实际上不存在!

这可能也有用:

struct KeyHash
{
    size_t operator()(const glm::ivec3& k)const
    {
        return std::hash<int>()(k.x) ^ std::hash<int>()(k.y) ^ std::hash<int>()(k.z);
    }
};
struct KeyEqual
{
    bool operator()(const glm::ivec3& a, const glm::ivec3& b)const
    {
        return a.x < b.x || (a.x == b.x && a.y < b.y) || (a.x == b.x && a.y == b.y && a.z < b.z);
    }
};
typedef unordered_map<glm::ivec3, Chunk, KeyHash, KeyEqual> ChunkMap;

遍历键也输出1,1,1

for (auto it : chunks) {
    logVector(it.first);
}

你的KeyEqual没有实现平等。将其替换为:

return a.x == b.x && a.y == b.y && a.z == b.z;