如果值大于 1,我将 map(Key-Value pair) 中的值减 1
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Creating a map with 4 element
map<int,int> m;
m[1]=1;
m[2]=2;
m[3]=1;
m[4]=3;
//Printing the output
for(auto x: m)cout<<x.first<<" "<<x.second<<endl;
//Applying substraction
for(auto x: m)
{
if(x.second>1)
{
x.second--;
}
}
cout<<"After subtraction operation: \n";
for(auto x: m)cout<<x.first<<" "<<x.second<<endl;
}
最佳答案
auto
使用与模板相同的类型推导规则,它们支持值类型,而不是引用类型。所以:
for (auto x : m)
相当于:
for (std::map<int,int>::value_type x : m)
这会复制键和值。然后您修改拷贝,实际 map 中的任何内容都没有更改。你需要的是:
for (auto& x : m)
(或者,如果你真的是受虐狂):
for (std::map<int,int>::value_type& x : m)
关于c++ - 为什么STL的Map中的值没有变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50467093/