繁体   English   中英

c++ 为几个无序映射运行循环

[英]c++ run a loop for several unordered maps

我是 C# 编码器,但我需要修复旧 c++ 代码中的某些内容。 我有 3 个无序映射和一个需要在每个 map 上运行的 for 循环。 显然,我不想重复循环代码 3 次。 在 c++ 中,如何将引用分配给每个 map,一个一个,然后运行循环(以便对地图的更改持续存在)?

std::unordered_map<std::wstring, std::int8_t> m_A;
std::unordered_map<std::wstring, std::int8_t> m_B;
std::unordered_map<std::wstring, std::int8_t> m_C;
// run over the 3 maps, one by one
// assign the map here
for (int=0; i<[relevant_map].size(); i++) {
    for (auto it = [relevant_map].cbegin(); it != [relevant_map].cend(); ++it) {
        ...

您可以将指向它们中的每一个的指针放在std::vector中,然后遍历每个条目。

std::vector<std::unordered_map<std::wstring, std::int8_t>*> all_maps;
all_maps.push_back(&m_A);
all_maps.push_back(&m_B);
all_maps.push_back(&m_C);

for (auto const& current_map : all_maps) {
// Your loops. current_map is a pointer to the current map.
}

你可能会这样做:

for (auto* m : {&m_A, &m_B, &m_C}) {
    for (/*const*/ auto& p : *m) {
        // ...
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM