我有以下代码:如何访问嵌套的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
我现在该如何通过设置和打印的所有元素循环?
集是三胞胎的集合,所以输出应该是这样的:
1 2 3
3 4 5
4 5 6
我有以下代码:如何访问嵌套的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
我现在该如何通过设置和打印的所有元素循环?
集是三胞胎的集合,所以输出应该是这样的:
1 2 3
3 4 5
4 5 6
您使用迭代器:
for (std::set<vector<int> >::iterator it = set_of_things.begin() ;
it != set_of_things.end() ;
it++)
{
// *it is a `vector<int>`
}
在C++ 11可以使用的,而不是auto
std::set<vector<int> >::iterator
。
如果你不修改迭代器,你应该使用const_iterator
来代替。
这是直接的,在C++ 11中引入的新的基于范围的for
循环:
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";
}
如果你不介意尾随空间:
for (auto const & v : set_of_things)
{
for (auto const & x : v)
{
std::cout << *it << " ";
}
std::cout << "\n";
}
或者使用the pretty printer:
#include <prettyprint.hpp>
#include <iostream>
std::cout << set_of_things << std::endl;
如果你有一个较老的编译器,你将必须拼写两个根据迭代器进行迭代。
so * it [0],* it [1],* it [2]应该是一个集合中的元素?这对我不起作用 – roshanvid
@ c0smikdebris我没有这么说。 '* it'是元素(类型为'vector') –
@ c0smikdebris'(* it)[0]'。 –