I have a vector of vector that is populated as follow:
Code:
typedef std::vector< std::vector<int> > matrix;
int main()
{
using namespace std;
matrix mat;
vector<int> vec;
for(int i = 0 ; i < 10 ; ++i){
for( int j = 0 ; j < 10 ; j++){
vec.push_back(i+j);
}
mat.push_back(vec);
}
}
I thought that this would print out the matrix:
Code:
// version 1:
for(matrix::iterator it = mat.begin() ; it != mat.end() ; ++it)
{
copy(it->begin(),it->end(),ostream_iterator<int> (cout,""));
cout << endl;
}
// version 2:
for(matrix::iterator it = mat.begin() ; it != mat.end() ; it++)
{
for(vector<int>::iterator it2 = it->begin() ; it2 != it->end() ;++it2)
cout << *it2;
cout << endl;
}
Using either version above, I got this instead of the matrix
Code:
0123456789
012345678912345678910
012345678912345678910234567891011
0123456789123456789102345678910113456789101112
012345678912345678910234567891011345678910111245678910111213
012345678912345678910234567891011345678910111245678910111213567891011121314
0123456789123456789102345678910113456789101112456789101112135678910111213146789101112131415
012345678912345678910234567891011345678910111245678910111213567891011121314678910111213141578910111213141516
012345678912345678910234567891011345678910111245678910111213567891011121314678910111213141578910111213141516891011121314151617
0123456789123456789102345678910113456789101112456789101112135678910111213146789101112131415789101112131415168910111213141516179101112131415161718
how should I access element of the vectors?
EDIT:: Nevermind,I found my mistake; i forgot to clear the "vec" when populating the matrix.
Code:
for(int i = 0 ; i < 10 ; ++i){
for( int j = 0 ; j < 10 ; j++){
vec.push_back(i+j);
}
mat.push_back(vec);
vec.clear(); <--- forgot this line ;(
}