我在对象的成员函数中有一个名为monthly_volumes 的 map ,每次完成对 map 的值字段的分配时,这些值都会重置为0(我之前初始化 map 的值)
for (auto i : monthly_volumes) {
i.second = get_monthly_volume(i.first, year);
cout << "Month check during loop" << i.first << ":" << i.second << endl;
}
for (auto i : monthly_volumes) {
//i.second = get_monthly_volume(i.first, year);
cout << "Month Check After loop" << i.first << ":" << i.second << endl;
}
这是
Output of the code
最佳答案
您需要使用引用遍历 map ,如下所示:
for (auto &i : monthly_volumes)
// changes to i, changes monthly_volumes
此外,在 c++17 中,您可以使用结构化绑定(bind)使代码更易于阅读:
for (auto &[k, v] : monthly_volumes) {
v = get_monthly_volume(k, year);
cout << "Month check during loop" << k << ":" << v << endl;
}
关于c++ - 为什么我退出循环后我的 map 值被重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61665211/