What is the difference between set and hashset in C++ STL?

前端 未结 5 854
时光说笑
时光说笑 2021-02-02 09:31

When should I choose one over the other? Are there any pointers that you would recommend for using the right STL containers?

5条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-02 10:14

    I don't think anyone has answered the other part of the question yet.

    The reason to use hash_set or unordered_set is the usually O(1) lookup time. I say usually because every so often, depending on implementation, a hash may have to be copied to a larger hash array, or a hash bucket may end up containing thousands of entries.

    The reason to use a set is if you often need the largest or smallest member of a set. A hash has no order so there is no quick way to find the smallest item. A tree has order, so largest or smallest is very quick. O(log n) for a simple tree, O(1) if it holds pointers to the ends.

提交回复
热议问题