cppreference.com says that complexity of range erase of std::map
is:
log(c.size()) + std::distance(first, last)
while erase for single element by iterator is amortized constant. So if I erase elements in a loop:
for( auto it = first; it != last; it = map.erase( it ) );
that should be linear on std::distance(first, last)
, and cplusplus.com agrees with that. What does standard say? Is this just typo on cppreference.com?
I only have the draft, but they are consistent with the draft:
n4594 Page 818.
log(c.size()) + std::distance(first, last)
When (first,last) is the entire range, that is the bigger factor, so this simplifies to
std::distance(first, last)
, which is linear, so this is consistent with your thoughts.it = map.erase( it )
is amortized constant. It's constant, plus a tiny bit for traversal and balancing. And when you add all those occasional tiny bits together overn
iterations, they sum to something inlog(c.size())
. You still have to add these to then
constant-time erasures themselves, for a total oflog(c.size()) + std::distance(first, last)
.In either case, what you want to use is
map.clear()
, which isO(n)
with a very small constant. It's far faster than erasing one at a time, since it can skip the balancing.