Search code examples
c++vectorstdinitializing

is there any difference between two methods that re-initializing vector?


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??


Solution

  • 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 ints 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 ints 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 ints and initializes their values to 3. Then this new vector is move assigned to vec, which in turn will throw away its memory of 2s and take the internal memory of the anonymous unnamed vector with its 3s, 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.