Reputation: 11
I am subtracting the value in map(Key-Value pair) by 1 if the value is grater than 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;
}
Upvotes: 0
Views: 72
Reputation: 28987
auto
uses the same rules for type deduction as templates do, and they favour value types, not reference types. So:
for (auto x : m)
is equivalent to:
for (std::map<int,int>::value_type x : m)
and this makes a copy of the key and the value. You then modify the copy, and nothing in the actual map is changed. What you need is:
for (auto& x : m)
(or, if you are really masochistic):
for (std::map<int,int>::value_type& x : m)
Upvotes: 5