您的位置:首页 > 其它

unordered_set VS set

2015-09-26 11:10 337 查看
在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好)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: