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]
...?
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.
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++.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With