【问题标题】:What type does it->first give?它->首先给出什么类型?
【发布时间】:2019-06-19 07:41:42
【问题描述】:

考虑以下代码:

  static std::unordered_map<std::string, Info> stringCollection;

  auto& [it, inserted] = stringCollection.try_emplace(pString);
  if (inserted) {
    it->second.str = &it->first;
  }
  return it->second;

这一行it-&gt;second.str = &amp;it-&gt;first 应该复制密钥(指针)的地址 - 但我似乎无法验证是否会出现这种情况(找不到参考)。基本上it-&gt;first给我一份或参考吗?

【问题讨论】:

  • 你可以自己猜:如果if-&gt;first 是一个值而不是一个引用会发生什么? &amp;it-&gt;first 将使用临时地址。

标签: c++ c++17 unordered-map


【解决方案1】:

您想删除auto 之后的&amp;,因为try_emplace 不返回引用:

auto [it, inserted] = stringCollection.try_emplace(pString);

在这种情况下,it 的类型是 std::unordered_map&lt;std::string, Info&gt;::iterator,它满足 LegacyForwardIterator,这意味着 LegacyInputIterator

  • it-&gt;m 等价于(*it).m
  • *it 返回std::iterator_traits&lt;It&gt;::reference(其中Itit 的类型)。

所以在你的例子中*it 的类型是std::pair&lt;const std::string, Info&gt;&amp;(一个引用),所以如果你访问它的成员first,你会得到一个const std::string 的引用,正如你所期望的。

【讨论】:

    【解决方案2】:

    迭代器保存键/值对。所以 ->first 会给出一个 std::string 作为参考

    【讨论】:

      猜你喜欢
      • 2019-05-30
      • 1970-01-01
      • 1970-01-01
      • 2019-04-05
      • 2011-05-30
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多