问题
std::set in C++ is not a real set in terms of data structures. std::unordered_set is a real set, but std::set is a binary search tree, more specifically a red-black tree. Why, then, is it called std::set? Is there some specific functionality that sets a std::set apart from a binary tree? Thanks.
回答1:
Why isn't std::set just called std::binary_tree?
Because
- Tree doesn't describe how the interface is used. Set does.
std::set
does not provide sufficient operations to be used as a general purpose search tree. It only provides an interface to a particular application of a search tree: The representation of a set.- Technically the standard doesn't specify that
std::set
is a binary search tree; although red-black BST may be the only data structure that can achieve the requirements imposed onstd::set
, and the interface has carefully been specified with that data structure in mind, the choice of internal data structure is an implementation detail. - For same reason
std::unordered_set
isn't calledstd::hash_table
.
std::unordered_set is a real set, but std::set is a binary search tree
std::unordered_set
isn't any more or less "real" than std::set
is. They are both sets with slightly different requirements and guarantees; One designed to be implementable using a tree, and another designed to be implementable using a hash table.
P.S. Tree and a hash table are not the only ways to represent a set. One internal data structure that can implement most - but not all - of std::set
is a sorted vector. Especially for small sets, a sorted vector can be much faster than std::set
.
来源:https://stackoverflow.com/questions/55375528/why-isnt-stdset-just-called-stdbinary-tree