C ++标准容器未插入新值的问题

问题描述

#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;
    }
}

在上述代码中,我试图在地图内部的集合中插入值5。但 it.second.insert(5); 不起作用

这是我得到的输出

Screen1
1
2
3

解决方法

在此循环中:

for(auto it : map)

变量itmap中每个元素的副本,因此修改it不会修改map

如果要修改元素,则需要执行以下操作:

for(auto &it : map)

这样it是对map中每个元素的引用。