C++17及以上如何通过范围for循环遍历不同类型的std::map集合
解决方案
你遇到的报错是因为std::map<int, std::string>和std::map<float, std::string>属于完全无关的类型,C++无法为初始化列表{intMap, floatMap}推导出统一的元素类型,因此范围for循环无法工作。
最简洁的C++17实现方案
使用可变参数模板+折叠表达式的编译期方案,零运行时开销,和手写两次遍历的性能完全一致:
#include <utility> // 通用遍历工具函数 template <typename Op, typename... Containers> void traverse_all(Op&& op, Containers&&... containers) { (std::forward<Op>(op)(std::forward<Containers>(containers)), ...); }
调用方式如下:
std::map<int, std::string> intMap = { {1, "one"}, {2, "two"}, {3, "three"} }; std::map<float, std::string> floatMap = { {1.0, "one"}, {2.0, "two"} }; // 统一遍历所有map traverse_all([](const auto& map) { for (const auto& [k, v] : map) { doSomething(k, v); } }, intMap, floatMap);
如果你不想单独定义工具函数,也可以用std::tuple+std::apply实现单行式调用:
#include <tuple> #include <functional> std::tuple all_maps{std::cref(intMap), std::cref(floatMap)}; std::apply([](const auto&... maps) { ([&] { for (const auto& [k, v] : maps.get()) { doSomething(k, v); } }(), ...); }, all_maps);
后续如果需要新增更多不同类型的map,只需要在参数列表里追加即可,不需要修改遍历逻辑。
内容的提问来源于stack exchange,提问作者locke14
相关产品推荐
相关产品推荐

