c++ run a loop for several unordered maps

Viewed 46

I'm a C# coder, but I need to fix something in older c++ code. I have 3 unordered maps, and a for loop that needs to run over each map. I don't want to repeat the loop code 3 times, obviously. In c++, how do I assign references to each map, ony by one, and run the loop (so that changes to the maps persist)?

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) {
        ...
2 Answers

You can put a pointer to each of them in a std::vector and then iterate over each entry.

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.
}

You might do:

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