在stackoverflow上看到一个问题,大概是问为什么有了平均查询O(1)的unordered_set我们还需要平均O(logN)的set呢?
首先我们需要知道set在STL底层是用红黑树来实现的,而unordered_set是基于hash。
在这里记录一下比较好的答案。
set uses less memory than unordered_set to store the same number of elements.(set更节省空间)
For a small number of elements, lookups in a set might be faster than lookups in an unordered_set.(小规模的话set或许更快)Even though many operations are faster in the average case for unordered_set, they are often guaranteed to have better worst case complexities for set (for example insert).(但总的来说基于hash的unordered_set还是快些)
That set sorts the elements is useful if you want to access them in order.
You can lexicographically compare different sets with <, <=, > and >=. unordered_sets are not required to support these operations.(set有序输出)People tend to overlook the fact that hashtables have O(1) average-case access time, meaning they can occasionally have big delays. The distinction can be important for real-time systems.
(这一点也很重要,对于实时系统来说tree的最糟糕的情况还是比hash好)