Unordered erase
I believe the most frequently used collection in C++ is vector. We know that a vector is great for everything except inserting or deleting items from random parts of the collection. This takes O(n) time, which is why I always feel a bit sad deleting something from the middle of a vector—since it has to shuffle about half of its contents just to shift slightly to the left.
There’s an idiomatic trick that can turn O(n) into O(1), but it comes at the cost of losing the element order in the vector. So, if you’re ready to pay the price, this simple trick is definitely the way to go:
| |
What did we do? First, we replaced the last element of the vector with the one marked for deletion, and then simply discarded it. Both operations are super cheap—it’s simple and beautiful.
Why the vector interface doesn’t have such a simple alternative to the usual erase method is unclear. In Rust, for example, it exists.
Well, we’ll have to create our own helper function for the code base:
| |
Source: PVS‑Studio