I'm trying to set a variable of unordered_map entry "chunk" by calling a function using a pointer to this entry. The pointer changes its value "chunkIndex", but the map entry not
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" is an unordered_map of type:
typedef unordered_map<glm::ivec3, Chunk, KeyHash, KeyEqual> ChunkMap;
Do you know why only the pointer changes its value, and not the referenced object?
Thanks in advance!
Update:
chunks.insert(make_pair(chunkIndex, Chunk()));
log((chunks.find(chunkIndex) == chunks.end()) ? "true" : "false");
This code outputs true, so it the inserted entry actually doesn't exist!
This might be useful too:
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;
Iterating through the keys also outputs 1, 1, 1
for (auto it : chunks) {
logVector(it.first);
}
Your KeyEqual
doesn't implement equality. Replace it with:
return a.x == b.x && a.y == b.y && a.z == b.z;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.