C++20 sections · 1024 units
Open in Course

Erasing Elements

Deleting map entries

Use m.erase(key) to remove an entry by its key. The method returns the number of elements removed, which is 0 if the key wasn't found or 1 if the entry was deleted. You can also erase by iterator: m.erase(m.find(key)).

This is useful when you already have the iterator from a previous find operation and don't need to search again. Erasing a single element runs in O(logn)O(\log n) time. Use m.clear() to remove all entries at once, which is faster than erasing elements one by one in a loop.