【问题标题】:Problem with C++ standard container not inserting new valuesC++ 标准容器不插入新值的问题
【发布时间】:2020-08-13 16:46:14
【问题描述】:
#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

【问题讨论】:

标签: c++ c++-standard-library


【解决方案1】:

在这个循环中:

for(auto it : map)

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

如果你想修改元素,你需要这样做:

for(auto &it : map)

所以it 是对map 中每个元素的引用。

【讨论】:

  • 如果是这样,it怎么会有成员second
  • @MarkRansom 副本仍然具有相同的类型,具有相同的成员。它只是没有引用同一个对象。
  • 所以你是说迭代器的副本不引用与原始迭代器相同的对象?我觉得这很难相信。
  • 不,我认为您误解了 it 是什么。它不是迭代器,而是容器中的实际元素(或它的副本)。迭代器的副本引用与原始迭代器相同的对象,就像指针一样。
  • @FrançoisAndrieux 感谢您和 cigien 将本应显而易见的事情冲击到我的脑海中。
猜你喜欢
  • 1970-01-01
  • 2019-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-22
  • 2011-10-24
  • 2013-01-23
相关资源
最近更新 更多