如何访问嵌套的stl元素?

ros*_*vid 0 c++ stl

我有以下代码:

set< vector<int> > set_of_things;
vector<int> triplet(3);

//set_of_things.push_back(stuff) - adding a number of things to the set
Run Code Online (Sandbox Code Playgroud)

我现在如何遍历集合并打印所有元素?

该集合是三元组的集合,因此输出应如下所示:

1 2 3 
3 4 5
4 5 6
Run Code Online (Sandbox Code Playgroud)

Ker*_* SB 5

这很简单for,在C++ 11中引入了新的基于范围的循环:

for (auto const & v : set_of_things)
{
    for (auto it = v.cbegin(), e = v.cend(); it != e; ++it)
    {
        if (it != v.cbegin()) std::cout << " ";
        std::cout << *it;
    }
    std::cout << "\n";
}
Run Code Online (Sandbox Code Playgroud)

如果你不介意尾随空格:

for (auto const & v : set_of_things)
{
    for (auto const & x : v)
    {
        std::cout << *it << " ";
    }
    std::cout << "\n";
}
Run Code Online (Sandbox Code Playgroud)

或使用漂亮的打印机:

#include <prettyprint.hpp>
#include <iostream>

std::cout << set_of_things << std::endl;
Run Code Online (Sandbox Code Playgroud)

如果您有一个较旧的编译器,则必须根据迭代器拼写两次迭代.

  • +1,但也许C++ 11的要求应该是明确的? (3认同)
  • @Jon:或许"遗留C++"要求应该在问题中明确?:-) (3认同)
  • 重点,但当目标是提供正确,实用和教育的解决方案,然后恕我直言,责任在知识渊博的一方.:-) (2认同)