为什么c++ STL不提供任何“树”容器,用什么代替最好?

我想将对象的层次结构存储为树,而不是使用树来增强性能……


当前回答

在某种程度上,std::map是一棵树(它被要求具有与平衡二叉树相同的性能特征),但它不公开其他树功能。不包含真正的树数据结构的原因可能只是不包含stl中的所有内容。stl可以被视为一个框架,用于实现您自己的算法和数据结构。

一般来说,如果你想要一个基本的库功能,而它不在stl中,修复方法是查看BOOST。

除此之外,还有很多库,这取决于树的需要。

其他回答

The STL's philosophy is that you choose a container based on guarantees and not based on how the container is implemented. For example, your choice of container may be based on a need for fast lookups. For all you care, the container may be implemented as a unidirectional list -- as long as searching is very fast you'd be happy. That's because you're not touching the internals anyhow, you're using iterators or member functions for the access. Your code is not bound to how the container is implemented but to how fast it is, or whether it has a fixed and defined ordering, or whether it is efficient on space, and so on.

因为STL不是一个“万能”库。本质上,它包含了建造东西所需的最小结构。

所有STL容器都可以与迭代器一起使用。你不能在树中使用迭代器,因为你没有遍历树的“唯一正确”方法。

使用树有两个原因:

你想用树形结构来镜像问题: 为此我们有boost图形库

或者您想要一个具有树形访问特征的容器 我们有

Std::map(和Std::multimap) Std::set(和Std::multiset)

基本上,这两个容器的特点是,它们实际上必须使用树来实现(尽管这实际上不是一个要求)。

还有这个问题: C树实现

可能与boost中没有树容器的原因相同。有许多方法可以实现这样的容器,没有一种好方法可以满足所有使用它的人。

需要考虑的一些问题:

节点的子节点数是固定的还是可变的? 每个节点的开销是多少?-即,你需要父指针,兄弟指针等。 提供什么算法?-不同的迭代器,搜索算法等。

最后的问题是,一个对所有人都足够有用的树容器,会因为太过重量级而无法满足大多数使用它的人。如果您正在寻找功能强大的东西,Boost Graph Library本质上是树库的超集。

下面是其他一些通用树的实现:

卡斯珀·彼得斯的树 Adobe的森林 核心:树