std :: map迭代器如何工作? [英] How does the std::map iterator work?
问题描述
C ++ STL类std :: map使用二叉树实现O(log(n))查找。但是对于树,迭代器的工作并不明显。 ++运算符在树结构中实际意味着什么?而下一个元素的概念在数组中有一个明显的实现,对我来说,它在树中不那么明显。如何实现树迭代器?
The C++ STL class std::map implements O(log(n)) look-up using a binary tree. But with trees, it's not immediately obvious how an iterator would work. What does the ++ operator actually mean in a tree structure? Whereas the concept of "next element" has an obvious implementation in an array, for me it's not so obvious in a tree. How would one implement a tree iterator?
推荐答案
对于一个遍历(可能也适用于其他人),如果你有一个父-pointer在你的节点你可以做一个非递归的遍历。应该可以只在你的迭代器中存储两个指针:你需要一个指示你在哪里,你可能(我现在不做研究)需要一个像以前的指针,所以你可以找出
For an inorder traversal (probably works for others too), if you have a parent-pointer in your nodes you can do a non-recursive traversal. It should be possible to just store two pointers in your iterator: you need an indication of where you are, and you'll probably (I'm not doing the research now) need something like a "previous" pointer so you can figure out your current movement direction (i.e. do I need to go into the left subtree, or did I just come back from it).
上一页将可能
这篇关于std :: map迭代器如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!