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

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


当前回答

使用树有两个原因:

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

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

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

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

还有这个问题: C树实现

其他回答

如果您正在寻找一个rb树实现,那么stl_tree.h可能也适合您。

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算法。

考虑到这一点,我尝试设计自己的树形数据结构,它将提供类似STL的接口,并将尽可能多地与现有的STL算法可用。

我的想法是树必须基于现有的STL容器,并且它不能隐藏容器,这样它就可以与STL算法一起使用。

树必须提供的另一个重要特性是遍历迭代器。

这是我能想到的:https://github.com/cppfw/utki/blob/master/src/utki/tree.hpp

下面是测试:https://github.com/cppfw/utki/blob/master/tests/unit/src/tree.cpp

"我想把对象的层次结构存储为树"

c++ 11来了又走了,他们仍然认为没有必要提供std::tree,尽管这个想法确实出现了(见这里)。也许他们没有添加的原因是,在现有容器的基础上构建自己的容器非常简单。例如……

template< typename T >
struct tree_node
   {
   T t;
   std::vector<tree_node> children;
   };

一个简单的遍历将使用递归…

template< typename T >
void tree_node<T>::walk_depth_first() const
   {
   cout<<t;
   for ( auto & n: children ) n.walk_depth_first();
   }

如果您想要维护一个层次结构,并且希望它与STL算法一起工作,那么事情可能会变得复杂。您可以构建自己的迭代器并实现一些兼容性,但是许多算法对于层次结构没有任何意义(例如,任何改变范围顺序的东西)。即使是在层次结构中定义一个范围也可能是一件混乱的事情。

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