【问题标题】:Assigning to a map iterator causes value change without being a reference分配给映射迭代器会导致值更改而不是引用
【发布时间】:2018-05-28 23:29:42
【问题描述】:

我不明白为什么在 std::map 中分配给迭代器->秒会修改映射中的值

#include <typeinfo>
#include <map>
#include <iostream>

int main() {
  std::map<int, int> lol;
  lol[2] = 33;

  auto it = lol.find(2);

  it->second = 91; // This changes the map's value

  std::cout << typeid(it->second).name(); // This just shows 'int', not a reference

  std::cout << lol[2]; // 91

  return 0;
}

it-&gt;second 不只是一个 int 而不是一个引用吗?

【问题讨论】:

  • Typeid 不会告诉你它是否是参考。
  • @JakeFreeman 即使使用这里的技术stackoverflow.com/questions/81870/… 也不起作用
  • @Barry 事实上,它不会。来不及修改,我就删了。

标签: c++ standard-library


【解决方案1】:

it-&gt;second 不只是一个 int 而不是一个引用吗?

是的,它只是一个int*it 给你一个std::pair&lt;int const, int&gt;&amp;,对map 中节点的实际值的引用。但对second 的成员访问实际上只是一个int。特征“是引用”和特征“可分配给”是不等价的 - 您可以分配给非引用,并且有些引用是您不能分配的。 it-&gt;second 为您提供int 类型的左值,您可以通过它进行分配,方式相同:

int i = 4;
i = 5; // i is not a reference, but you can assign it here

也就是说,typeid() 无论如何都不会给你一个引用类型,因为引用和 cv 限定从类型分析中被删除了。另见my answer here

说,你可能想看的是decltype((it-&gt;second))(是的,括号加倍,乐趣加倍)。实际上,这给了您int&amp;,因为该表达式是int 类型的左值。

【讨论】:

  • 知道了,所以我要取消引用节点,然后直接修改值.. 对吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多