【问题标题】:Iterate map<string, unique_ptr<Foo> >迭代 map<string, unique_ptr<Foo>>
【发布时间】:2019-09-30 23:32:07
【问题描述】:

我看到这里有一个非常接近的问答:Iterating over a container of unique_ptr's 但是,当它涉及地图的迭代时,我看不到如何避免复制/分配 unique_ptr。

当我迭代映射时,例如,为了简单起见,使用 c++17,假设 x 是 Foo 的 int 类型的公共成员变量:

map<string, unique_ptr<Foo> > my_map;
for (auto const& [key, val] : my_map) {
  val->x = 1;
}

我得到了错误:

constexpr std::pair<_T1, _T2>::pair(const std::pair<_T1, _T2>&) [with _T1 = const std::__cxx11::basic_string<char>; _T2 = std::unique_ptr<Foo>]’ is implicitly deleted because the default definition would be ill-formed:

我确实看到另一个帖子 (Cannot iterate over map whose elements hold a uniq_ptr) 这样做:

map<string, wrapper_struct > my_map;

其中 wrapper_struct 是一个内部带有 unique_ptr 的结构。我的问题是:有没有更简单的解决方案?

【问题讨论】:

标签: c++11 unique-ptr stdmap


【解决方案1】:

您可以使用对迭代器本身的 const 引用而不是对中的元素。

for (const auto& it : my_map) {
    auto ptr_to_unique_foo = it.second.get();
}

【讨论】:

  • 我写了一个更简单的测试代码,你的方法有效。所以这是其他错误,可能与我的特殊 Foo 类有关。挖...
  • 不需要对迭代器使用 const 引用。迭代器本身会做得很好。你有一个对存储的 value 的 const 引用,而不是一个迭代器,这也很好。
猜你喜欢
  • 2013-12-18
  • 1970-01-01
  • 1970-01-01
  • 2016-01-12
  • 2015-12-05
  • 2018-01-06
  • 1970-01-01
  • 2013-11-08
  • 1970-01-01
相关资源
最近更新 更多