Iterator Invalidation Rules

You're iterating over a std::map and need to erase certain elements during iteration. Which approach is correct in C++11 and later?

A

Call erase freely inside the loop, since std::map iterators are never invalidated

B

Use a range-based for loop and call map.erase(key) inside the loop body

C

Use an iterator loop and capture the return value of erase: it = map.erase(it)

D

Collect keys to delete into a separate vector, then erase after the loop, because erasing during iteration is always undefined behavior