3

根据以下链接 - http://www.cplusplus.com/reference/set/set/ C++ 的 STL 中的集合通常实现为二叉搜索树,我能够在集合等情况下衡量数据类型的行为整数或字符或浮点数或字符串,因为在这些情况下,很容易看到 BST 排序被强加于集合元素,但考虑到集合的二叉搜索树数据结构实现,我无法想象以下内容使用二叉搜索树实现的数据类型:

  1. set<vector<int>>set<vector<string>>set<vector<double>>set<list<int>>
  2. set<map<int, int>>
  3. set<stack<int>>

或者对于许多其他数据类型,如何为这些类型分配内存以及如何维护顺序。

此外,我无法弄清楚以下内容,每当将新向量添加到集合中时,集合数据类型是否会在内部检查集合中的所有向量的相似性或所有映射的相似性,这些是我无法做到的弄清楚。如果有人可以帮助我想象这些概念,那就太好了。

提前致谢 :)

4

2 回答 2

3

The set uses a strict weak ordering to determine the position of each element. This is done using std::less<T> by default. This will result in a call to operator<(const T&, const T&). Now, containers such as std::vector have such operators, which just perform a lexicographical comparison of all the elements. That is how an std::set<std::vector<int>> can work out of the box.

When a new element is inserted, the set does not have to check all the elements. Insertion is a logarithmic complexity operation, which is why the implementation tends to be a self-balancing binary tree (I phrase it with this rather odd causality because the C++ standard does not specify what the implementation should be like, just how it should behave.)

于 2013-04-07T16:04:42.190 回答
0

A set<T> always works the same, regardless of what concrete type T is. On an insertion, it figures out where in the tree* to place the new element by comparing it with various existing elements using std::less<T> (which by default calls operator<). If operator< isn't overloaded for T, then it won't compile.

Therefore, the details of how to order instances of T are abstracted from the details of how to maintain a set.


* Note that std::set doesn't have to use a tree; that's just a typical implementation.

于 2013-04-07T16:04:30.150 回答