简体   繁体   English

如果不满足循环条件,如何执行一段代码?

[英]How to execute a piece of code if the condition of a loop is not met?

Suppose I have a tree and I want to keep going left from the current node.假设我有一棵树,我想继续从当前节点向左走。 And if there is no left from the current node, I wanna keep going right.如果当前节点没有左边,我想继续往右走。 otherwise return.否则返回。 To do something like that I'll have to write something like that:要做这样的事情,我必须写这样的东西:

if (node->left != nullptr)
    while (node->left != nullptr)
        node = node->left;
else if (node->right != nullptr)
    while (node->right != nullptr)
        node = node->right;
else return;

As you can see I had to write the condition twice.正如你所看到的,我不得不写两次条件。 Can I write something like this:我可以写这样的东西:

while (node->left != nullptr)
    node = node->left;
else while (node->right != nullptr)
    node = node->right;
else return;

Also it would be helpful if I can use while with if.如果我可以在 if 中使用 while 也会很有帮助。 Something like this:像这样的东西:

while (...) ...
else if (...) ... 
else while (...) ...
else ...

Edit: Just realized that the example of trees is not a good one.编辑:刚刚意识到树的例子不是一个好例子。 But generally can I do something like that or not?但通常我可以做这样的事情吗?

I mean, this will do what you are asking for我的意思是,这将满足您的要求

if (node->left != nullptr)
    while (node->left != nullptr)
        node = node->left;
else if (node->right != nullptr)
    while (node->right != nullptr)
        node = node->right;
else return;

but maybe is better to check that node is not nullptr (if you're not doing before)但也许更好地检查node不是nullptr (如果你以前没有这样做)

if (node && node->left != nullptr)
    while (node->left != nullptr)
        node = node->left;
else if (node && node->right != nullptr)
    while (node->right != nullptr)
        node = node->right;
else return;

Yes, this is certainly possible in this case.是的,在这种情况下这当然是可能的。 In fact, you can even avoid writing the if and while twice.事实上,您甚至可以避免编写ifwhile两次。

Notice that the only difference between the pieces of code, is which Node member is being used (ie are you branching left or right).请注意,代码片段之间的唯一区别是正在使用哪个Node成员(即您是向左还是向右分支)。 So, depending on which branch you want to follow, you can take a pointer to that member, like this:因此,根据您要遵循的分支,您可以获取指向该成员的指针,如下所示:

Node* Node::* branch = node->left != nullptr ? &Node::left : &Node::right;

and then unconditionally follow that branch, like this:然后无条件地遵循该分支,如下所示:

while (node->*branch != nullptr)
    node = node->*branch;

In general, when you have two identical pieces of code, you have to decide on a case by case basis which parts of it can be abstracted, and whether the resulting code is improved by it or not.通常,当您有两段相同的代码时,您必须根据具体情况决定可以抽象其中的哪些部分,以及生成的代码是否被它改进。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM