how to reintialize a vector

Z

zl2k

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
 
M

mlimber

zl2k said:
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
 
M

mlimber

mlimber said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,260
Messages
2,571,038
Members
48,768
Latest member
first4landlord

Latest Threads

Top