set vs unordered_set for fastest iteration

前端 未结 5 1529
无人及你
无人及你 2021-02-13 02:18

In my application I have the following requirements -

  1. The data structure will be populated just once with some values (not key/value pairs). The values may be r

5条回答
  •  隐瞒了意图╮
    2021-02-13 03:04

    An unordered-set uses a hash-table to provide near O(1) time searching. This is done by using a hash of the key to calculate the offset of the element-you-are-seeking (keys) from the beginning of the dataset. Unless your dataset is small (like chars) different keys may have the same hash (a collision).

    To minimize collisions a unordered-set will have to keep the data-store fairly sparsely populated. This means that finding a key will most be O(1) time (unless there is a collision).

    However when iterating through a hash-table our iterator will encounter a lot of unused space in our datastore which will slow down the finding of the next element by our iterator. We could link adjacent elements in the hash-table with extra pointers but I do not think an unordered-set does so.

    In light of the above, I will suggest you use a sorted vector for your "set". Using bisections you can search the store in O(log n) time and iterating through the list is trivial. A vector has the added advantage that the memory is contiguous so you are less likely to experience cache misses.

提交回复
热议问题