jyoti harsh
jyoti harsh

Reputation: 13

Problem with C++ standard container not inserting new values

#include <iostream>
#include<bits/stdc++.h>
using namespace std;

int main() {
    unordered_map<string,set<int>> map;
    set<int> s;
    s.insert(1);
    s.insert(2);s.insert(3);
    map.insert(make_pair("Screen1",s));
    for(auto it : map)
    {
        cout<<it.first<<endl;
        it.second.insert(5);
    }
    for (auto i : map["Screen1"])
    {
        cout<<i<<endl;
    }
}

In the above stated code I am trying to insert a value 5 in the set inside the map. but it.second.insert(5); doesnot do the trick

here is the output that i am getting

Screen1
1
2
3

Upvotes: 1

Views: 75

Answers (1)

cigien
cigien

Reputation: 60268

In this loop:

for(auto it : map)

the variable it is a copy of every element in map, so modifying it doesn't modify map.

If you want to modify the elements, you need to do:

for(auto &it : map)

so that it is a reference to every element in map.

Upvotes: 7

Related Questions