为什么c++ STL不提供任何“树”容器,用什么代替最好?
我想将对象的层次结构存储为树,而不是使用树来增强性能……
为什么c++ STL不提供任何“树”容器,用什么代替最好?
我想将对象的层次结构存储为树,而不是使用树来增强性能……
当前回答
"我想把对象的层次结构存储为树"
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算法一起工作,那么事情可能会变得复杂。您可以构建自己的迭代器并实现一些兼容性,但是许多算法对于层次结构没有任何意义(例如,任何改变范围顺序的东西)。即使是在层次结构中定义一个范围也可能是一件混乱的事情。
其他回答
如果您正在寻找一个rb树实现,那么stl_tree.h可能也适合您。
所有STL容器在外部都被表示为具有一种迭代机制的“序列”。 树不遵循这个成语。
因为STL不是一个“万能”库。本质上,它包含了建造东西所需的最小结构。
使用树有两个原因:
你想用树形结构来镜像问题: 为此我们有boost图形库
或者您想要一个具有树形访问特征的容器 我们有
Std::map(和Std::multimap) Std::set(和Std::multiset)
基本上,这两个容器的特点是,它们实际上必须使用树来实现(尽管这实际上不是一个要求)。
还有这个问题: C树实现
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.