我有以下代碼:如何訪問嵌套的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]'。 –