【问题标题】:How to iterate map containing set in c++?如何在 C++ 中迭代包含集合的地图?
【发布时间】:2016-03-19 02:17:36
【问题描述】:

我有一个包含一组整数的地图,如下所示:

std::map<int, std::set<int>> haha;

但是每个集合中的元素数量是未知的。现在我想迭代整个地图并将键和值打印到文件"f"。该怎么做?

【问题讨论】:

    标签: c++ loops dictionary iteration


    【解决方案1】:
    for (std::map<int, std::set<int> >::const_iterator i = haha.begin(); i != haha.end(); ++i) {
        int key = i->first;
        const std::set<int>& values = i->second;
    }
    

    【讨论】:

    【解决方案2】:

    我所知道的最简洁的方式(如果没有,请告诉我):

    for(auto const& pair : haha)
    {
        std::cout << pair.first << " : ";
        std::copy(pair.second.begin(), pair.second.end(), std::ostream_iterator(std::cout, " "));
        std::cout << std::endl;
    }
    

    或完全使用 range-for 循环:

    for(auto const& pair : haha)
    {
        std::cout << pair.first << " : ";
    
        for(auto x : pair.second)
            std::cout << x << " ";
    
        std::cout << std::endl;
    }
    

    如果你想把它打印到一个文件中,只需创建std::ofstream 并用它的名字替换std::cout,因为这是C++,而不是C。我们不想看到fprintfs 在这个漂亮的代码。

    【讨论】:

    • @LogicStuff 非常感谢。但是第一种方式,如果我想fprintf它是不是很困难?
    • @LogicStuff 我的错我错过了 for 循环
    • @yobichi 如果您确实想要“打印到文件”而不是“调用fprintf()”,您可以打开std::ofstream 并做同样的事情。
    【解决方案3】:
    for (auto mapitr = haha.begin(); itr != haha.end(); ++mapitr) {
       std::cout << mapitr->first << std::endl;
       for (auto setItem: mapitr->second) {
         std::cout << setitem << std::endl;
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-03
      • 2012-03-02
      • 1970-01-01
      • 2010-10-18
      相关资源
      最近更新 更多