Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterator for 2d vector

How to create iterator/s for 2d vector (a vector of vectors)?

like image 969
miroslavec Avatar asked Nov 23 '09 17:11

miroslavec


2 Answers

Although your question is not very clear, I'm going to assume you mean a 2D vector to mean a vector of vectors:

vector< vector<int> > vvi; 

Then you need to use two iterators to traverse it, the first the iterator of the "rows", the second the iterators of the "columns" in that "row":

//assuming you have a "2D" vector vvi (vector of vector of int's) vector< vector<int> >::iterator row; vector<int>::iterator col; for (row = vvi.begin(); row != vvi.end(); row++) {     for (col = row->begin(); col != row->end(); col++) {         // do stuff ...     } } 
like image 75
Austin Hyde Avatar answered Sep 19 '22 19:09

Austin Hyde


You can use range for statement to iterate all the elements in a two-dimensional vector.

vector< vector<int> > vec; 

And let's presume you have already push_back a lot of elements into vec;

for(auto& row:vec){    for(auto& col:row){       //do something using the element col    } } 
like image 20
ShuaiYu8 Avatar answered Sep 21 '22 19:09

ShuaiYu8