Re: vector of vectors
On Jan 2, 2:41 pm, happy <hppymit...@yahoo.com> wrote:
I wanted to make a vector of vectors of int so I tried
following :
#include<iostream>
#include<vector>
int main()
{
vector<vector<int> >vec;
for(int i=0;i<2;i++)
{
vector<int>newVec;
vec.push_back(newVec);
for(int j=0;j<3;j++)
{
std::cin>>num;
vec[i].push_back(num); // Here vec[i] works but newVec.push_back
// (num) doesn't work. Why?
Both "work" equally well, but they do different things. What
you've written above pushes back on the vector you've inserted
into vec. newVec.push_back pushes back on newVec. After you've
copied the empty vector into vec[i]. And of course, since
newVec immediately goes out of scope, and is destructed, the
push_back don't end up having any visible effect in your code.
Roughly speaking, you have two choices: you can do the push_back
on newVec before inserting it into vec, e.g.:
vector< int > newVec;
for ( int j = 0; j < 3; ++ j ) {
int num;
std::cin >> num;
if ( ! std::cin ) {
// Handle error, probably with a throw or by
// exiting...
}
newVec.push_back( num );
}
vec.push_back( newVec );
, or you can do as you've done. In your case, I find the above
clearer and more logical, but if the vectors being copied are
large, it can cause a performance hit. In such cases, you might
consider using your version, but with vec[i] replaced by
vec.back(). (No point in indexing if what you want is the last
entry.)
}
}
}
--
James Kanze