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

c++ run a loop for several unordered maps

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

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) {
        // ...
    }
}