>,c++11,unique-ptr,stdmap"/>

首页 > 解决方案 > 迭代地图>

问题描述

我看到这里存在一个非常接近的 Q/A:Iteration 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:

我确实看到另一篇文章(无法迭代其元素包含 uniq_ptr 的地图)正在做:

map<string, wrapper_struct > my_map;

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

标签: c++11unique-ptrstdmap

解决方案


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

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

推荐阅读