【问题标题】:c++ run a loop for several unordered mapsc ++为几个无序映射运行循环
【发布时间】:2020-05-19 22:53:23
【问题描述】:

我是一名 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


    【解决方案1】:

    你可以这样做:

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

      【讨论】:

        猜你喜欢
        • 2018-01-23
        • 2019-10-25
        • 2011-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多