public member function

std::vector::emplace

<vector>
template <class... Args>
iterator emplace (const_iterator position, Args&&... args);
Construct and insert element
The container is extended by inserting a new element at position. This new element is constructed in place using args as the arguments for its constructor.

This effectively increases the container size by one.

This causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity.

Because vectors use an array as their underlying storage, inserting elements in positions other than the vector end causes the container to move all the elements that were after position to their new positions. This is generally an inefficient operation compared to the one performed for the same operation by other kinds of sequence containers (such as list or forward_list). See emplace_back for a member function that extends the container directly at the end.

Parameters

position
Position in the container where the new element is inserted.
Member type const_iterator is a random access iterator type.
args
Arguments passed to the constructor of the new element.

Return value

An iterator that points to the newly emplaced element.

Member type iterator is a random access iterator type.

If a reallocation happens, the storage is allocated using the container's allocator, which may throw exceptions on failure (for the default allocator, bad_alloc is thrown if the allocation request does not succeed).

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// vector::emplace
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector = {10,20,30};

  auto it = myvector.emplace ( myvector.begin()+1, 100 );
  myvector.emplace ( it, 200 );
  myvector.emplace ( myvector.end(), 300 );

  std::cout << "myvector contains:";
  for (auto& x: myvector)
    std::cout << ' ' << x;
  std::cout << '\n';

  return 0;
}

Output:
myvector contains: 10 200 100 20 30 300

Complexity

Linear on the number of elements after position (moving).

If a reallocation happens, the reallocation is itself up to linear in the entire size.

Iterator validity

If a reallocation happens, all iterators, pointers and references related to this container are invalidated.
Otherwise, only those pointing to position and beyond are invalidated, with all iterators, pointers and references to elements before position guaranteed to keep referring to the same elements they were referring to before the call.

Data races

The container is modified.
If a reallocation happens, all contained elements are modified.
Otherwise, none of the elements before position is accessed, and concurrently accessing or modifying them is safe.

See also