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.
auto it = v.insert(v.begin() + 1, 42); // iterator to the new element it = v.erase(it); // iterator to what followed it
Try it
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.
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
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
posfrom another vector, orerase(end()), is undefined behavior; so is erasing a range whosefirstcomes afterlast. - 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.
insertmay throwstd::bad_allocor 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::dequeorstd::list, or swap-and-pop for unordered data:v[i] = std::move(v.back()); v.pop_back();. erasein a loop: the classic bug isfor (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()anderasekeep capacity; useshrink_to_fit()to ask for it back.eraseafterstd::remove:std::removeonly moves the kept elements forward and returns the new end; the vector's size does not change until you callerase.- Inserting a range from itself is not allowed; copy it first.
emplacein the middle may still build a temporary internally before shifting elements, so the saving overinsertis smaller than foremplace_back.- Negative offsets:
v.begin() + iwith a signediis fine; with an out-of-rangeithe arithmetic itself is undefined. - Efficient bulk insertion: one range insert shifts the tail once, while repeated single inserts shift it every time.