Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prefer unordered_set over vector

Tags:

c++

stl

Is it safe to say that if I don't want duplicates in my container, and I don't care about element position as I only want to iterate through the container, then I should use an unordered_set instead of vector?

like image 413
Pilpel Avatar asked Nov 23 '15 16:11

Pilpel


2 Answers

Is it safe to say that if I don't want duplicates in my container, and I don't care about element position as I only want to iterate through the container, then I should use an unordered_set instead of vector?

No, it is not. It depends on many factors. For example if you seldom add new elements but iterate over container quite often it would be preferable to use std::vector and maintain uniqueness manually. There also could be other factors affecting your decision. But normally yes you may prefer std::unordered_set as it simplifies your program.

like image 133
Slava Avatar answered Oct 14 '22 13:10

Slava


Not entirely. unordered_sets are not required to be contiguous containers; in the case where you'd frequently want to read all numerous values contained in the set, you may prefer std::vector on time-critic application.

std::unordered_set:

Internally, the elements are not sorted in any particular order, but organized into buckets. Which bucket an element is placed into depends entirely on the hash of its value. This allows fast access to individual elements, since once a hash is computed, it refers to the exact bucket the element is placed into.

But in the general case, I'd say Yes.

like image 45
YSC Avatar answered Oct 14 '22 11:10

YSC