为什么对我的变量所做的更改在下一次迭代之前不存在?

Why don't the changes to my variables survive until the next iteration?

我想更新存储在循环内 map 中的 struct 的实例,但是对实例变量的更改不会在循环迭代(在循环内一次迭代,新变量得到正确设置,在下一次操作中它们被重置为初始值)。

这是我正在做的事情的简化版本:

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;
}

您的问题是您正在创建找到的区域的副本,而不是更新在地图中找到的对象。

RegionOverFrames foundRegion = it->second;
//               ^ copy created

您应该改用引用:

RegionOverFrames &foundRegion = it->second;
//               ^ use reference