I use two methods when I re-initialize vector
vector<int> vec(1000, 1);
//first
vec.assign(1000, 2);
//second
vec = vector<int>(1000, 3);
I think these two methods are produce same result, but I found that the second method takes up less memory.
Is there something difference between these two method??
The difference is how the internal memory of the
std::vectoris handled.With
You created a new
std::vectorcalledvec. It allocates memory to hold 1000ints and initializes their values to1.In the first method:
You then tell
vecto reuse that allocated memory, where the 1000ints live. They are simply overwritten by values of2.In the second method:
You actually do two things - you create a new
std::vectorwhich allocates memory for 1000ints and initializes their values to3. Then this new vector is move assigned tovec, which in turn will throw away its memory of2s and take the internal memory of the anonymous unnamed vector with its3s, because its a so-called rvalue.The overall memory consumption should be the same in the end, although when using the 2nd method, for a moment you have 2 allocated memory regions of 1000
ints each, alive at the same time.