Ashish Kumar Jha
Ashish Kumar Jha

Reputation: 11

Why the value in Map of STL is not changing?

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;

}

Output

Upvotes: 0

Views: 72

Answers (1)

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

Related Questions