2016-11-29 137 views
0

所以我正在学习stlibrary和图表,所以我发现图表可以表示为列表的向量,可能是这样的,其中1 2 3 4 5 6是顶点,从顶点1我可以去数2,从3到6等循环遍历列表向量

1 2 3 4 5 6 
2 6 1 2 
     2 

但是,我已经保存在矢量列表中的这些价值观,我怎么可能通过它循环,得到图表?我的向量列表被称为_verticesEdges。

等,以得到一个输出这样的:

顶点1:2

顶点2:

顶点3:6

顶点4:1 2

顶点5:

Vertice 6:2

感谢您的帮助!

+1

注意,['STL!= std'](http://stackoverflow.com/questions/5205491/whats-the-difference-between-stl-and-c-standard-library)。你将不得不显示一些代码来获得帮助。请提供[mcve]。 – user463035818

+0

我会搜索如何遍历一个向量。另外,正如@ tobi303所说,你需要在这里展示一些代码来获得帮助。 –

回答

0

像这样的事情

std::vector<std::list<int>> vecOfLists; 
// fill vecOfLists; 
for (size_t i = 0; i < vecOfLists.size(); ++i) { 
    std::cout << "Vertice " << i + 1 << ": "; 
    for (int num : vecOfLists[i]) { 
     std::cout << num << " "; 
    } 
    std::cout << std::endl; 
} 

我使用平常for通过列表迭代,因为需要指标,并使用range-based for通过列表迭代,因为这是更好的和现代的方式,通过整个容器,如果迭代你不需要索引。

1
Assuming you have stored from index 1 to n (that means size of 0th index of your vector is zero), where n is number of vertices, 

for (int i = 1; i <= n; i++) 
{ 
    cout << "Vertex " << i << ": "; 

    for (int j=0; j< _verticesEdges[i].size(); j++) 
    cout << _verticesEdges[i][j] << " "; 
    cout << "\n"; 
}