Saturday, April 27, 2013

iterating through 2d "vector" c++

http://stackoverflow.com/questions/1784573/iterator-for-2d-vector


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 ...
    }
}

Multi Dimensional Array

The more STL savvy coder will opt for a vector-of-a-vector approach to MD arrays, rather than Nested New:

1
2
3
4
// to make a [5][6] array:
vector< vector<int> > stillevil( 5, vector<int>(6) );

stillevil[2][3] = 1;


Not a lot to say about this one. Like Nested New it's incompatible with other MD array flavors. If you need to pass this array to a function, none of the above functions will work.

Also, like Nested New, it's inefficent in that is requires additional memory and has double indirection.

On the plus side, you don't need cleanup code, and the allocation code is not as ugly (but still pretty ugly!)


1 comment: