指向unordered_map表项的指针改变了,但表项不变
C++ Pointer to unordered_map entry changes, but entry not
我试图通过使用指向该条目的指针调用函数来设置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_maptypedef 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;
相关文章:
- 变量没有改变?通过向量的函数调用
- 如何改变c++应用程序的视觉效果
- C++在不同线程中改变向量
- 如何访问和改变存储在矢量C++中的对象
- 在C++行尾写一个分号或多个分号是否会改变任何内容
- 为什么字符串的 move() 会改变内存中底层数据的位置?
- 为什么 c++ 动态数组的大小没有改变?
- 为什么提升图库的 read_graphviz() 函数会改变节点的索引
- 在向量内更改变量的值不会改变其在向量外的值
- 为什么 GCC 不能假设 std::vector::size 在这个循环中不会改变?
- 改变或缩放两个正态分布以具有特定的相关系数
- 当我使用CHAR_INFO结构时,控制台会无缘无故地改变颜色
- 为什么我的函数接受"std::string"进行排序不会改变它?
- MFC:你能在CDateTimeCtrl中改变自旋的加速度吗?
- 为什么切换 for 循环的顺序会显著改变执行时间?
- 使用可变参数模板改变模板参数
- C++中物体改变识别的设计模式?
- 通过从构造函数中的'this'复制的指针改变常量对象
- C++11:具有互斥锁的线程看到原子变量的值发生变化,尽管这是唯一可以改变它的代码
- 如果没有重新散列,为什么 unordered_set::begin() 会改变?