如何在 C++ 中迭代包含集合的映射?

How to iterate map containing set in c++?

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

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

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

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

我知道的最简洁的方法(如果不知道请告诉我):

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 在这个漂亮的代码中。

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