为什么对变量的更改不能保留到下一次迭代?
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
相关文章:
- 在一次迭代中从 txt 文件中读取多行
- 高级选择排序 - 在一次迭代中搜索两个元素
- foor 循环的最后一次迭代中的指针更改
- 循环中本地对象的析构函数是否保证在下一次迭代之前被调用?
- ifstream不会在下一次迭代中打开文件
- C++如何使用lambda表达式来捕获上一次迭代的值
- 如何强制循环执行另一次迭代到零并关闭循环
- C 一次迭代所有仿制药
- 具有两个变量的"for"循环,一个变量每次迭代递增,每隔一次迭代递增
- while(getline(myReadFile, temp, ':')) 执行一次迭代太多导致向量越界
- 如何在C++中的while循环中存储上一次迭代
- 如何将while循环的每一次迭代都分配给线程
- 为什么用于解析我读取的行的内部循环每隔一次迭代就会通过外部读取循环跳过
- 有没有办法在一次迭代中进行任意数量的正则表达式替换
- z 阶曲线中的下一次迭代
- OpenCV神经网络一次训练一次迭代
- While循环在一次迭代后终止
- c++为下一次迭代保留索引
- 在while循环的下一次迭代中重写Const char *
- 通过一次迭代删除字符串中的所有逗号、句点和小写字母