How to create iterator/s for 2d vector (a vector of vectors)?
Assuming you mean an STL iterator, and a custom container that implements a generic 2D array of objects, this is impossible. STL iterators support only increment and decrement (i.e. "next" an "previous") operations, where motion through a 2D set requires four such primitives (e.g. left/right/up/down, etc...). The metaphors don't match.
What are you trying to do?
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 ...
}
}
Assuming you mean a vector of vectors, and you have std::vector
in mind, there's no built in way to do it, as iterators only support increment and decrement operations to move forward and backwards.
A 2D vector is a matrix, and so you'd need two iterator types: a row iterator and a column iterator. Row iterators would move "up" and "down" the matrix, whereas column iterators would move "left" and "right".
You have to implement these iterator classes yourself, which is not necessarily a trivial thing to do. Unless, of course, you simply want to iterate over each slot in the matrix, in which case a double for loop using index variables i
and j
will work just fine. Depending on your needs (your post is a bit lacking in content here), you may want to use boost::numeric::ublas::matrix
, which is a matrix class from the Boost linear algebra library. This matrix class has built-in row and column iterators, which make it generally easy to iterate over a matrix.