Modern C++ idoms and recipes


Working with vectors

Remove multiple items from a vector

We looked already at the Erase-Remove Idiom in the Januar 2016 Meeting. The Erase-Remove Idiom is considered the correct way of removing multiple items from a standard library container.

Deleting items from an unsorted vector in $O(1)$

Deleting an element from the middle of an std::vector with the Erase-Remove idiom takes $O(n)$, because the resulting gap must be filled by moving all the items after the gap to the left. This might be expensive if the items are complex and/or very large. If preserving the order of the items is not important, the deletion can be optimized.

Keep std::vector sorted

Sometimes you want a sorted vector to be still sorted after insertion of an element. Try to implement a sorted insertion.

Implement insert_sorted method
Create your playground on
This playground was created on, our hands-on, knowledge-sharing platform for developers.
Go to