0Pricing
C++ Academy · Lesson

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

  1. std::vector Basics: push_back size capacity
  2. Iterating Vectors: index range-for iterators
  3. Modifying Vectors: insert erase clear
  4. Vector vs std::array vs C Array
← Back to C++ Academy