c++对多个无序图进行循环运行。

问题描述 投票:2回答:2

我是一名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) {
        ...
c++ loops unordered-map
2个回答
2
投票

你可以这样做。

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

2
投票

你可以把指向每个地图的指针放到 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.
}
© www.soinside.com 2019 - 2024. All rights reserved.