Is the old vector get cleared? If yes, how and when?
I have the following code:
void foo()
{
vector<double> v(100,1); // line 1
// some code
v = vector<double>(200,2); // line 2
// some code
}
what happened to the vector of size 100 after the second line? Is it gets cleared by itself? If the answer is yes, how and when it is cleared?
By the way, is there any other "easy and clean" ways to change the vector as in line 2? I don't want things like
v.resize(200);
for (int i=0; i<200; i++) v[i] = 2;
Another question. What if the vector is a member of a class:
class A{
public:
vector<double> data;
A(int size, double value)
{
data = vector<double>(size,value);
}
};
A object(10,1);
// some code
object = A(20,2); // ** What happened to the old object.data? **
// so开发者_StackOverflow中文版me code
In the assignment, first a temporary vector object is created that contains 200 times the element 2
. Then this temporary object is assigned to v
: The vector v
removes all the elements it currently contains and copies the contents of the temporary vector object. At the end of the statement the temporary vector object is destroyed again.
To do this more concisely without creating a temporary object you can use the assign()
method:
v.assign(200, 2);
精彩评论