c++11 - 迭代地图>
问题描述
我看到这里存在一个非常接近的 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 的结构。我的问题是:有没有更简单的解决方案?
解决方案
您可以使用对迭代器本身的 const 引用而不是对中的元素。
for (const auto& it : my_map) {
auto ptr_to_unique_foo = it.second.get();
}
推荐阅读
- ios - Flutter Google Maps 插件在 iOS 上无法正常工作
- selenium-ide - 如何在 Chrome 上修复 Katalon Recorder
- apache2 - .htaccess 在默认 apache2 目录的子目录中
- python - 如何递归输出给定长度的0和1的排列?
- postgresql - 如何知道 Postgresql 服务器在什么操作系统/平台上运行?
- augmented-reality - AR.js:增加稳定性的多个标记?
- javascript - 设置默认单选输入和相应的复选框
- java - 我的缩进有问题吗?
- javascript - 如果对象具有属性,则对对象数组进行排序
- javascript - Javascript validation on hidden field is not working in MVC