【发布时间】:2016-07-09 00:23:56
【问题描述】:
我有一个函数可以将一个值插入到一个向量映射的空映射中。 (该特定结构可以满足我对渲染对象进行一些复杂排序的需求)。
但是,当我向其中添加内容时,我的数据似乎在结构中的某个位置丢失了。
我的方法代码(带有一点上下文)在这里:
typedef unsigned int ComponentUID;
//For the purposes of this example, assume the map is completely empty
std::map<ComponentUID, std::map<float, std::vector<GameObjectPtr>>> renderOrderMap;
void Render::addGameObjectToMap(GameObjectPtr objectPtr) {
//Expose the pointer for ease of use
GameObject *object = objectPtr.get();
//Set up component local variables
RenderComponent *component = object->getRenderComponent();
ComponentUID uid = component->getComponentUID();
//Get object's render level (arbitrary float)
float renderLevel = object->getRenderLevel();
//Find the location of the component UID in the render order map
std::map<ComponentUID, std::map<float, std::vector<GameObjectPtr>>>::iterator objectLocation = renderOrderMap.find(uid);
//If the object doesn't exist in the map
if (objectLocation == renderOrderMap.end()) {
//Add a new pair with the component UID and a fresh float/vector map and set the object location to the iterator pointing to it
objectLocation = renderOrderMap.insert(std::pair<ComponentUID, std::map<float, std::vector<GameObjectPtr>>>(uid, std::map<float, std::vector<GameObjectPtr>>())).first;
printf("Inserted pair");
}
//Get the map at the value of the object location iterator
std::map<float, std::vector<GameObjectPtr>> objectMapping = objectLocation->second;
//Find the render level in the map
std::map<float, std::vector<GameObjectPtr>>::iterator vectorLocation = objectMapping.find(renderLevel);
//If the object doesn't exist in the map
if (vectorLocation == objectMapping.end()) {
//Add a new pair with the render level and a fresh GameObjectPtr vector and set the vector location to the pair's iterator
vectorLocation = objectMapping.insert(std::pair<float, std::vector<GameObjectPtr>>(renderLevel, std::vector<GameObjectPtr>())).first;
/*
* These two should equal the same value, because they should call the same method on the same object
*/
printf("Mapping size: %i", objectMapping.size()); //Outputs 1
printf("ExtraMapSize0: %i", renderOrderMap.find(uid)->second.size()); //Outputs 0
}
//Add the game object to the vector
std::vector<GameObjectPtr> objectVector = vectorLocation->second;
objectVector.push_back(objectPtr);
}
问题出现在两条 printf 语句的底部附近。理论上它们应该指向同一个对象,但第一次调用返回的值与第二次不同。
只是我的代码有问题,还是我从根本上误解了迭代器的工作原理?
【问题讨论】:
-
你为什么不对
map::insert的返回值测试.second?
标签: c++ dictionary iterator