vector emplace() function in C++ STL
The vector::emplace() is an STL in C++ which extends the container by inserting a new element at the position. Reallocation happens only if there is a need for more space. Here the container size increases by one.
template iterator vector_name.emplace (const_iterator position, element);
The function accepts two mandatory parameters which are specified as below:
- position – It specifies the iterator pointing to the position in the container where the new element is to be inserted.
- element- It specifies the element to be inserted in the vector container.
Return value: The function returns an iterator that points to the newly inserted element.
Below programs illustrates the above function:
The vector elements are: 15 10 20 30
The vector elements are: 10 20 30 16
The vector elements are: 10 20 16 30
Regular insertion using shift operation in arrays V/s emplace( ) function :
a) If want to insert an element at some specific position between the first and last index, we have to shift all the elements next to that specific index. So, if want to keep our code precise so emplace( ) would be a good choice. In terms of Time Complexity both take the same linear time which is directly dependent on the number of shift operations.
Content of a: 1 2 3 4 5 Content of v: 1 2 3 4 5