vector iterator giving extra output

i am just initialising a vector using while and printing the result but its giving extra 0 in the begining of the data.i don't know why this is happening.plz help
vector< vector<int> >::iterator iter_ii;
vector<int>::iterator iter_jj;
int n;
vector< vector<int> >vi(2,vector<int>(2,0));
while(cin>>n)
{if(n==0)break;
else vi[0].push_back(n);




// else if(n==3) vi[2].push_back(n);

}
for(iter_ii=vi.begin(); iter_ii!=vi.end(); iter_ii++)
{ cout<<"----"<<endl;
for(iter_jj=(*iter_ii).begin(); iter_jj!=(*iter_ii).end(); iter_jj++)
{
cout << *iter_jj << endl;
}
}

every time results preceeds extra 0 s
Those extra zeros are there because you're initializing your matrx to be 2x2:

1
2
3
4
5
6
vector< vector<int> >vi(2,vector<int>(2,0));  // this line

/*
  vector<int>(2,0)  makes a vector with 2 elements, each 0
  vi(2,vector<int>(2,0));  <-- makes 2 of these vectors, effectively making a 2x2 matrix of zeros
*/


this may be what you intended, but remember that push_back() adds new elements and does not replace elements. Perhaps what you meant to do with this line:

 
else vi[0].push_back(n);


Is something like this instead where you replace the element at [0][0]:

 
vi[0][0] = n;


As it stands now, the original zeros placed there by the initialization are never changed -- you only add new numbers to the end the vector.
thnx Disch ..i got the error.
Topic archived. No new replies allowed.