In the previous lesson, we pushed elements to the back of
the vector, because that is the easiest thing to do, and
usually that's all we need.
But vector also offers us a way to insert elements at
the specific position in the array.
I created a new vector and reserved a place for five subjects, and then I filled
it up by emplacing new subjects. Notice that one of them is a duplicate, and
this is not a mistake, we will need this for later.
Now, let's say that I want to insert another element at the
specific position, maybe at the index of two. To do that, we can
use the insert function, which takes in the required position and
the object we want to insert.
However, this position needs to be defined with an iterator.
So if the begin iterator is the address of the first element,
then we can add two to get the address of the element at the index of two,
and I will create some random subject with the ID of eight.
This will put the element at that specific position in the array, but this
insert function works kind of like a push_back function.
It will move the subject from the main scope to the vector.
Since we don't want that, let's immediately make this more
efficient by using the emplace function instead. Emplace
function to the insert function is what the emplace_back
function is to the push_back function.
It will directly instantiate the subject on the vector by passing the right
parameters. Just like with emplace_back function, you can add these
constructor parameters as arguments of the emplace function.
Okay, let's now compile this to see what happens.
It seems that the emplace function worked, this subject with the ID of
eight is placed at the third position in the array,
but the move constructor was invoked five times.
This is because the old internal array had the capacity of
five, and once we insert this new element,
this new array needs to have six elements, so, resizing needs to happen.
The new array of six elements will first create the new object
with the parameterized constructor. and it will do so in the
specified position in the array.
After that,
all of the elements from the old array need to be moved to the new array.
So this is why we see five move constructors,
because we need to move five elements.
Of course, if you know that some emplacing will happen in the future,
you can reserve more memory. In that case, only the
elements that really have to move will be moved, and no
new array will have to be created.