2012-09-05 154 views
0

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

回答

1

您使用迭代器:

for (std::set<vector<int> >::iterator it = set_of_things.begin() ; 
     it != set_of_things.end() ; 
     it++) 
{ 
    // *it is a `vector<int>` 
} 

在C++ 11可以使用的,而不是autostd::set<vector<int> >::iterator

如果你不修改迭代器,你應該使用const_iterator來代替。

+0

so * it [0],* it [1],* it [2]應該是一個集合中的元素?這對我不起作用 – roshanvid

+0

@ c0smikdebris我沒有這麼說。 '* it'是元素(類型爲'vector') –

+2

@ c0smikdebris'(* it)[0]'。 –

5

這是直接的,在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; 

如果你有一個較老的編譯器,你將必須拼寫兩個根據迭代器進行迭代。

+3

+1,但也許C++ 11的要求應該是明確的? – Jon

+3

@Jon:或者「遺留C++」要求在問題中應該是明確的? :-) –

+2

需要採取的一點,但是當目標是提供正確,實用和教育解決方案時,恕我直言,責任就在更有知識的一方。 :-) – Jon