
[英]How to iterate std::map values in my own order / the order they were inserted?
[英]How to iterate in order for a custom map?
我正在寻找建立自己的地图类。 (其行为将与C ++ STL完全一样)我希望能够按键值顺序遍历所有元素。
我将地图实现为不平衡的二进制搜索树。
所以我的问题是如何有效地进行迭代器增量。 一种低效的方法是遍历树中的每个元素以找到下一个最低的键。 有更快的方法吗?
谢谢。
这取决于实现细节。 如果不平衡的二进制搜索树的节点具有“父”指针,则可以使用该指针进行遍历。 您的++ iterator实现可能看起来像这样:
if (current_node.has_right_child()) {
// We go to the right subtree of the current node and
// take the smallest element of that subtree.
current_node = current_node.right_child();
while (current_node.has_left_child()) {
current_node = current_node.left_child();
}
} else {
// We have to go up. If the current element is the left child of the parent,
// we can just go to the right child of the parent.
// If it is the right child, we have to go further up
while (true) {
if (!current_node.has_parent()) {
// We got up to the root and never found a right child.
// So we are at the end of the iteration.
current_node = NULL;
break;
}
Node* parent = current_node.parent();
bool is_left_child = parent.left_child() == current_node;
current_node = parent;
if (is_left_child) {
// if this was the left child, then the parent is the correct next element.
break;
}
// if this was the right child, we have to go further up
// until we leave this subtree, so we continue iterating.
}
}
如果您的二叉树没有父节点,则可以将父节点存储在迭代器中。 也就是说,您可以维持一个向量父母; 您将当前节点的父节点存储到根节点中。 如果仍然需要这样做,我可以提供一个实现,但是由于您使用父指针编辑了“非父指针”版本,因此您似乎拥有父指针。 因此,我将其丢弃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.