Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through a 2d Vector row

I am working on a homework assignment for my C++ class.

I am trying to iterate through a 2d multidimensional vector. I have all the data in the 2d vector which is size 7x7 i.e. 0-6 by 0-6,.

Problem is I need to output the contents of the 2d vector in the order of alphaV[0][0], alphaV[1][0], alphaV[2][0], etc.

When I try to use a nested For loop to process this vector I run into problems whereby the rows of the vector will not iterate, that is to say they remain at index 0.

So it keeps repeating alphaV[0][0], alphaV[0][0], alphaV[0][0], etc.

How do I go about iterating the columns in that pattern [0][0], [1][0], [2][0] ...?

like image 578
user2943507 Avatar asked Nov 01 '13 01:11

user2943507


People also ask

How do I iterate through a 2D vector?

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.

How do you find the rows and columns of a 2D vector?

vector_name. size() gives you the numbers of column in a 2D vector and vector_name[0]. size() gives you the numbers of rows in a 2D vector in C++.


1 Answers

Iterate over the vectors, this is the standard way of traversing containers:

void printVector(const std::vector< std::vector<int> > & vec)
{ 

    std::vector< std::vector<int> >::const_iterator row; 
    std::vector<int>::const_iterator col; 

    for (row = vec.begin(); row != vec.end(); ++row)
    { 
         for (col = row->begin(); col != row->end(); ++col)
         { 
            std::cout << *col; 
         } 
    } 

} 

More information on iterators can be found here: http://www.cplusplus.com/reference/iterator/

like image 171
AngelCastillo Avatar answered Oct 17 '22 05:10

AngelCastillo