std::vector::assign

S

scooter

what happens memory wise with this scenerio:

std::vector<int> vecInt(20, 999);

VecInt.assign(20, 0);


do all the 999 values get overwritten or does the vector reassign the
memory lso?

thanks
 
B

Buster Copley

scooter said:
what happens memory wise with this scenerio:

std::vector<int> vecInt(20, 999);

VecInt.assign(20, 0);

You have the parameters backwards.
do all the 999 values get overwritten or does the vector reassign the
memory lso?

Do you want the memory to be freed and reallocated?
If so, I know that

std::vector <int> vecInt (999, 20);

{
std::vector <int> temp ();
temp.swap (vecInt)
}

will do it. IIRC, vector::assign works identically to
constructing a new vector and using operator=, and in
that case (again IIRC) the memory is not guaranteed to
be released and reallocated.

Regards,
Buster.
 
T

tom_usenet

You have the parameters backwards.


Do you want the memory to be freed and reallocated?
If so, I know that

std::vector <int> vecInt (999, 20);

{
std::vector <int> temp ();

The above declares a function called temp, which isn't what you
wanted.
temp.swap (vecInt)
}

The canonical way to do this (which very few people seem to get right
for some reason), is:

std::vector<int>().swap(vecInt);

Tom
 
B

Buster

tom_usenet said:
The above declares a function called temp, which isn't what you
wanted.

Yes, silly of me. Thanks.
The canonical way to do this (which very few people seem to get right
for some reason), is:

std::vector<int>().swap(vecInt);

I have a question about that. I thought I read somewhere that a
temporary is not modifiable. Isn't the result of the expression
'std::vector <int> ()' (when it is an expression...) a temporary?
So what am I missing?

Regards,
Buster.
 
T

tom_usenet

I have a question about that. I thought I read somewhere that a
temporary is not modifiable. Isn't the result of the expression
'std::vector <int> ()' (when it is an expression...) a temporary?
So what am I missing?

Temporaries are modifiable, it's just that you can't bind them to
non-const references. e.g. this is illegal:

vecInt.swap(std::vector<int>());

Here a temporary is passed as the argument to swap. This argument is a
non-const reference, so the code is illegal.

So, to summarize, you can call member functions (const or non-const)
on non-const temporaries, but you can't bind them to non-const
references. This is why the standard swap technique works, but some
alternatives don't.

Tom
 

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

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top