Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Containers

std::vector::insert and erase

Reference for vector::insert, emplace and erase: inserting single values and ranges, erasing by iterator, return values, complexity and invalidation.

insert places one or more new elements before a given position, emplace builds one in place there, and erase removes the element or range at a position. Because a vector's elements are contiguous, each of these has to shift every element after the position, so they cost O(n) in the worst case. Only operations at the end (push_back, pop_back) are O(1).

All three return an iterator, and you should use that returned iterator rather than the one you passed in: it is valid even if the buffer was reallocated, and after erase it refers to the element that followed the removed one.

C++
auto it = v.insert(v.begin() + 1, 42);    // iterator to the new element
it = v.erase(it);                         // iterator to what followed it

Try it

C++ Inserting values, counts and ranges

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ Erasing one element, a range and in a loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Syntax

C++
iterator insert(const_iterator pos, const T& value);
iterator insert(const_iterator pos, T&& value);
iterator insert(const_iterator pos, size_type count, const T& value);
iterator insert(const_iterator pos, InputIt first, InputIt last);
iterator insert(const_iterator pos, std::initializer_list<T> list);
template <class... Args> iterator emplace(const_iterator pos, Args&&... args);

iterator erase(const_iterator pos);
iterator erase(const_iterator first, const_iterator last);

// C++20 free functions
size_type std::erase(vector<T, A>& v, const U& value);
size_type std::erase_if(vector<T, A>& v, Pred pred);
Name Description
pos The element before which to insert, or the element to erase. end() is valid for insert, not for erase.
count, value Insert count copies of value.
first, last A half-open range [first, last). For insert it must not point into the same vector.
list Values to insert, in order.

Returns: insert and emplace return an iterator to the first inserted element (or pos if nothing was inserted). erase returns an iterator to the element after the last one removed (possibly end()). std::erase/std::erase_if return the number of elements removed.

Errors / undefined behavior:

  • A pos from another vector, or erase(end()), is undefined behavior; so is erasing a range whose first comes after last.
  • Using an iterator to or beyond the insertion or erasure point afterwards (other than the returned one) is undefined. Insertion that reallocates invalidates all of them.
  • insert may throw std::bad_alloc or an exception from the element's copy/move; the basic guarantee applies (the strong one only for single-element insertion at the end).

Usage notes

  • Cost: inserting or erasing at the front is O(n); if you do it often, use std::deque or std::list, or swap-and-pop for unordered data: v[i] = std::move(v.back()); v.pop_back();.
  • erase in a loop: the classic bug is for (auto i = v.begin(); i != v.end(); ++i) v.erase(i);, which uses an invalidated iterator. Use the returned iterator, std::erase_if, or the erase-remove idiom; see erase-remove.
  • clear() and erase keep capacity; use shrink_to_fit() to ask for it back.
  • erase after std::remove: std::remove only moves the kept elements forward and returns the new end; the vector's size does not change until you call erase.
  • Inserting a range from itself is not allowed; copy it first.
  • emplace in the middle may still build a temporary internally before shifting elements, so the saving over insert is smaller than for emplace_back.
  • Negative offsets: v.begin() + i with a signed i is fine; with an out-of-range i the arithmetic itself is undefined.
  • Efficient bulk insertion: one range insert shifts the tail once, while repeated single inserts shift it every time.