Does clear() affect the bucket count of std::unordered_set?
Asked Answered
G

1

7

There are plenty of answers with std::vector, but what about std::unordered_set?

My real question (closely related) is this; is it efficient to reuse the same unordered set by clearing it before each use, if I reserve what I know to be a reasonable size beforehand?

Gracia answered 4/9, 2014 at 23:46 Comment(4)
I'd say this would be implementation specific. The standard only specifies that clear() erases all elements in the container.Soong
I think the same argument applies as for std::vector::reserve: bucket_count is part of the observable state; it is allowed to be changed on insertion, but it's not explicitly allowed to change on rehash or reserve (or even on erase as far as I can see..).Smallpox
@dyp: you've lost me... "bucket_count... not explicitly allowed to change on rehash or reserve" - the latter exist to allow the number of bucket (thus bucket_count()) to be modified - the former directly accepts a new number of buckets (but is subject to a size() / max_load_factor() sanity check) and the latter derives it from a number of anticipated elements and the current max_load_factor. "explicit" or not that's what they do.Scroggins
@TonyD Hmm seems I was confused. Of course it is explicitly allowed to change on insertion, rehash and reserve, but not clear nor erase.Smallpox
A
6

Formal answer is: it depends on implementation.

Informal answer is: unordered_set inside has an array (of some kind) of buckets, and most likely the implementation is consistent with vector, so this array won't be deleted when clear() is called. So calling clear() most likely will give some benefit.

Austronesia answered 5/9, 2014 at 0:5 Comment(1)
Thanks, as with Jonathan Potter's answer; it's good to know that it's not specified. Using reserve before each use is already a gain in performance anyway.Gracia

© 2022 - 2024 — McMap. All rights reserved.