Modifying Vectors: insert erase clear
Insert, erase and clear elements while keeping iterator invalidation rules in mind.
Inserting at the End
The fastest insert: push_back or emplace_back — both add to the end in amortized O(1).
Inserting at an Arbitrary Position
insert(pos, value) shifts everything after pos right. O(n) operation.
std::vector<int> v = {1, 2, 4, 5};
v.insert(v.begin() + 2, 3); // {1, 2, 3, 4, 5}All lessons in this course
- std::vector Basics: push_back size capacity
- Iterating Vectors: index range-for iterators
- Modifying Vectors: insert erase clear
- Vector vs std::array vs C Array