views:

212

answers:

3

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

A: 

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?

Andy Ross
+3  A: 

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 ...
    }
}
Austin Hyde
Sorry that my question wasn't so clear but this is exactly what I wanted. Although I'm getting compiler error with this code:cannot convert from 'std::_Vector_iterator<_Ty,_Alloc>' to 'int' on for (row = vvi.begin(); row != vvi.end(); row++) {
miroslavec
always use pre increment operators. With vectors it's likely that it wont matter when using a vector but it's a bad habit to get into. Life would be much clearer if it had been ++C instead of C++.
caspin
A: 

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.

Charles Salvia
Exactly what I meant, 2D vector matrix with (now I know that two) iterators. I thought questions was clear :( ... anyway I'm quite new to vectors and I have to use them in this work.Now another problem is that error I posted in above comment (formating is shit). Can't assign value to first (row) iterator as because that type mismatch.
miroslavec