Reputation: 91
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]
...?
Upvotes: 8
Views: 27427
Reputation: 466
Only for giving complete example for the AngelCastillo's answer
#include <iostream>
#include <vector>
using namespace std; //to stop using std every time
int main(){
vector<int> vts;
vector<vector<int>> vec; //multidimensional vector
//simple vector iteration
vts.push_back(10);
for(vector<int>::iterator itv = vts.begin();itv != vts.end(); ++itv ){
cout << *itv << "\n";
}
//how to add multidimensional objects
vector<int> tmp;
tmp.push_back(20);
vec.push_back(tmp);
vector<vector<int>>::const_iterator row;
vector<int>::const_iterator col;
for (row = vec.begin(); row != vec.end(); ++row)
{
for (col = row->begin(); col != row->end(); ++col)
{
cout << *col << "\n";
}
}
//same iteration another way
for(vector<vector<int>>::iterator row = vec.begin();row != vec.end(); ++row ){
for(vector<int>::iterator col = row->begin();col != row->end(); ++col ){
cout << *col << "\n";
}
}
}
Upvotes: 1
Reputation: 2435
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/
Upvotes: 17