我想更新一个struct
的实例,我将其存储在循环中的map
中,但实例变量的更改不会在循环的迭代中生效(在一次迭代,新变量得到适当设置,在下一个操作中,它们被重置为初始值。)
以下是我正在做的简化版本:
map<int, RegionOverFrames>* foundRegions = new map<int, RegionOverFrames>;
for (int i = 0; i < frames.size(); i++) {
// find all regions in current frame
map<int, RegionOverFrames> regionsInCurrentFrame;
for (Region region: currentFrame.regions) {
if (foundRegions->count(region.regionId) == 0) {
RegionOverFrames foundRegion;
foundRegion.regionId = region.regionId;
regionsInCurrentFrame[region.regionId] = foundRegion;
(*foundRegions)[region.regionId] = foundRegion;
}
else if (foundRegions->count(region.regionId) > 0) {
RegionOverFrames foundRegion = (*foundRegions)[region.regionId];
regionsInCurrentFrame[region.regionId] = foundRegion;
}
}
// update found regions (either by adding weight or setting the end index)
for (auto it = foundRegions->begin(); it != foundRegions->end(); it++) {
RegionOverFrames foundRegion = it->second;
// the region that was found before is also present in this frame
if (regionsInCurrentFrame.count(foundRegion.regionId) > 0) {
float weight = currentFrame.getRegion(foundRegion.regionId).getWeight();
foundRegion.accumulatedWeight += weight; // this update of accumulatedWeight is not present in the next loop, the accumulatedWeight only gets assigned the value of weight here, but in the next iteration it's reset to 0
}
}
}
这是否与我使用迭代器it
访问map<int, RegionOverFrames>* foundRegions
中的对象或使用指针声明foundRegions
的事实有关存储在堆上?
注意RegionOverFrames
是一个简单的struct
,如下所示:
struct RegionOverFrames {
int regionId;
double accumulatedWeight;
}
答案 0 :(得分:3)
您的问题是您正在创建找到的区域的副本,而不是更新地图中找到的对象。
RegionOverFrames foundRegion = it->second;
// ^ copy created
您应该使用引用:
RegionOverFrames &foundRegion = it->second;
// ^ use reference