470,811 Members | 1,113 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,811 developers. It's quick & easy.

how to reintialize a vector

hi, there
Suppose I have declared a vector in the header file

vector<int> v1;
vector< vector<int> > v2;

Now I need to reinitialize the vector somewhere later to different
sizes. How can I do that for v2? For v1, I can always say
v1.assign(10,0);
to set its size to 10 and populate with 0s.

For v2, can I reinitialize it with known size of one dimension (row)
and with unknown size of another dimension (collumn)? How? (Or maybe I
can always declare the unknow size to 1 since the vector can grow?)

Thanks ahead.

zl2k

May 16 '06 #1
2 2675
zl2k wrote:
hi, there
Suppose I have declared a vector in the header file

vector<int> v1;
vector< vector<int> > v2;

Now I need to reinitialize the vector somewhere later to different
sizes. How can I do that for v2? For v1, I can always say
v1.assign(10,0);
to set its size to 10 and populate with 0s.

For v2, can I reinitialize it with known size of one dimension (row)
and with unknown size of another dimension (collumn)? How? (Or maybe I
can always declare the unknow size to 1 since the vector can grow?)

Thanks ahead.

zl2k


You can do it in a loop:

v2.resize( newRows );
for( unsigned n=0; n < v2.size(); ++n )
{
v2[ n ].resize( newCols );
}

Or you could do it less efficiently but more concisely:

v2.swap( vector< vector<int> >( newRows, vector<int>( newCols ) );

Cheers! --M

May 16 '06 #2
mlimber wrote:
Or you could do it less efficiently but more concisely:

v2.swap( vector< vector<int> >( newRows, vector<int>( newCols ) );


....add an extra closing parenthesis in there.

M

May 16 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

9 posts views Thread by {AGUT2}=IWIK= | last post: by
9 posts views Thread by luigi | last post: by
8 posts views Thread by Ross A. Finlayson | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.