C ++指向unordered_map条目的指针更改,但不是条目

时间:2015-07-23 14:22:32

标签: c++ pointers reference

我正在尝试通过使用指向此条目的指针调用函数来设置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);
}

1 个答案:

答案 0 :(得分:0)

您的KeyEqual没有实现平等。替换为:

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