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::vector
is handled.
With
std::vector<int> vec(1000, 1);
You created a new std::vector
called vec
. It allocates memory to hold 1000 int
s and initializes their values to 1
.
In the first method:
vec.assign(1000, 2);
You then tell vec
to reuse that allocated memory, where the 1000 int
s live. They are simply overwritten by values of 2
.
In the second method:
std::vec = std::vector<int>(1000, 3);
You actually do two things - you create a new std::vector
which allocates memory for 1000 int
s and initializes their values to 3
. Then this new vector is move assigned to vec
, which in turn will throw away its memory of 2
s and take the internal memory of the anonymous unnamed vector with its 3
s, 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 int
s each, alive at the same time.