gpt4 book ai didi

c++ - 二叉树节点子节点的高效选择

转载 作者:行者123 更新时间:2023-11-28 03:38:22 25 4
gpt4 key购买 nike

我有以下代码:

        NodePtr bestChild = (diff < 0) ? node->child1 : node->child2;
NodePtr otherChild = (diff < 0) ? node->child2 : node->child1;

有没有更有效的方法来设置 bestChild 和 otherChild 变量?

注意 difffloat 并且比较是相当长的操作。

我还尝试了以下解决方案:

        NodePtr bestChild = (diff < 0) ? node->child1 : node->child2;
NodePtr otherChild = (bestChild == node->child2) ? node->child1 : node->child2;

在这种情况下我不做比较,但我不确定这是最好的方法。

最佳答案

或者:

NodePtr bestChild, otherChild;
if (diff < 0)
{
bestChild = node->child1;
otherChild = node->child2;
}
else
{
bestChild = node->child2;
otherChild = node->child1;
}

NodePtr children[2] = (diff < 0) ? {node->child1, node->child2} : {node->child2, node->child1};

或者保持原样,因为编译器可能会为您完成此操作。

关于c++ - 二叉树节点子节点的高效选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10187921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com