std::vector<T> · C++
insert / emplace
Inserts before pos, shifting later elements right.
iterator insert(const_iterator pos, const T& value); template<class... Args> iterator emplace(const_iterator pos, Args&&... args);
Complexity
| Best case | O(1) at end() |
|---|---|
| Worst case | O(n) |
| Extra space | O(1) amortized |
Linear in the number of elements between pos and end(), which are moved one slot right.
Tested example
std::vector<std::string> v{"a", "c", "d"};
auto it = v.insert(v.begin() + 1, "b"); // shifts "c" and "d" right
assert(*it == "b");
assert((v == std::vector<std::string>{"a", "b", "c", "d"}));
// `it` and every iterator at or after the insertion point may now be invalid
Parameters
- pos
- An iterator into this vector (end() appends).
Behaviour
- Returns
- An iterator to the inserted element.
- Errors and preconditions
- std::bad_alloc; exceptions from T's constructors or assignments.
- Changes
- size() increases by 1.
- Memory and invalidation
- Reallocation invalidates everything; otherwise iterators and references at or after pos are invalidated.
See it step by step: the Dynamic arrays: capacity, resizing and amortized append lesson has an interactive 3D visualizer of the same mechanism.