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?

braX
  • 11,506
  • 5
  • 20
  • 33
Jonathan H
  • 7,591
  • 5
  • 47
  • 80
  • 1
    I'd say this would be implementation specific. The standard only specifies that `clear()` erases all elements in the container. – Jonathan Potter Sep 04 '14 at 23:59
  • 1
    I think the [same argument applies as for `std::vector::reserve`](http://stackoverflow.com/a/18467916): `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..). – dyp Sep 05 '14 at 00:06
  • @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. – Tony Delroy Sep 05 '14 at 02:45
  • @TonyD Hmm seems I was confused. Of course it is explicitly allowed to change on insertion, `rehash` and `reserve`, but not `clear` nor `erase`. – dyp Sep 05 '14 at 09:38

1 Answers1

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.

Anton Savin
  • 40,838
  • 8
  • 54
  • 90
  • 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. – Jonathan H Sep 05 '14 at 00:08