Search⌘ K

Delete Items from an Unsorted Vector in Constant Time

Explore how to efficiently delete elements from an unsorted vector in C++ by moving the last element into the deleted position and then shrinking the vector. This lesson helps you understand a constant time technique that optimizes vector modifications when element order is not required.

We'll cover the following...

Using the uniform erasure functions (or the erase-remove idiom) to delete items from the middle of a vector takes O(n)O(n) (linear) time. This is because elements must be shifted from the end of the vector to close the gap of the deleted items. If the order of items in the vector is not important, we can optimize this process to take O(1)O(1) (constant) time. Here’s how.

...