1
#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
François Andrieux
  • 28,148
  • 6
  • 56
  • 87

1 Answers1

7

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.

cigien
  • 57,834
  • 11
  • 73
  • 112
  • If this is the case, how is it that `it` has a member `second`? – Mark Ransom Aug 13 '20 at 16:51
  • 1
    @MarkRansom A copy still has the same type, which has the same members. It just doesn't refer to the same object. – cigien Aug 13 '20 at 16:52
  • So you're saying a copy of an iterator doesn't refer to the same object as the original iterator? I find that hard to believe. – Mark Ransom Aug 13 '20 at 16:53
  • 1
    No, I think you're misunderstanding what `it` is. It's not an iterator, but the actual element in the container (or a copy of it). A copy of an iterator *would* refer to the same object as the original iterator, just like a pointer. – cigien Aug 13 '20 at 16:55
  • Yes, but the item in the question didn't include a `second` member. Thus my question. If things are as you say, it shouldn't have compiled. – Mark Ransom Aug 13 '20 at 16:56
  • Sure it does. The elements of a `map` are essentially `pair`s which have a `second` member. – cigien Aug 13 '20 at 16:58
  • @MarkRansom `it` is a `std::pair>`. The loop does not expose any iterators. In the case without a reference, the key and the entire `std::set` that is the value are copied to the pair. – François Andrieux Aug 13 '20 at 17:00
  • 1
    @FrançoisAndrieux thank you and cigien for pounding into my head what should have been obvious. – Mark Ransom Aug 13 '20 at 17:05