【发布时间】:2018-05-22 11:57:39
【问题描述】:
如果值大于 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;
}
【问题讨论】:
-
将
for(auto x: m)更改为for(auto &x: m)它正在制作副本,然后您正在更改副本的值而不是原始值。 -
@RichardCritten 发表您的评论作为答案
标签: c++ dictionary stl