为什么对变量的更改不能保留到下一次迭代?

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

本文关键字:一次 迭代 变量 保留 不能 为什么      更新时间:2023-10-16

我想更新我在循环内存储在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