以C ++编写一个递归函数的最好方法? [英] Best way to write a recursive function in C++?

查看:141
本文介绍了以C ++编写一个递归函数的最好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题
我想知道这是否是实现可变深度递归,这样我可以运行的每一步,并没有更好的/其他的解决方案,以说明问题的一个功能,一个可行的办法。
说明
假设我希望有一个功能,填补了数组无论是在模式
X,Y,X,Y,X,Y 其中x和y变量通过某种算法定义
的x,y,Z,X,Y,Z 其中x,y和z是由相同的算法定义的变量。

Question
I wish to know if this is a viable way to implement variable depth recursion so that I can run a function at each step and any better/other solutions to the description problem.
Description
Suppose I wish to have a function that fills an array either in pattern
x,y,x,y,x,ywhere x and y are variables defined by some algorithm
and x,y,z,x,y,z where x, y and z are variables defined by the same algorithm.

本应继续为所有数量的变量。这是实现它的可行方法。

This should continue for all number of variables. Is this a viable way to implement it.

void recurse_n(int n)
{
    while(n > 0)
    {
        --n;
        recurse_n(n);
        n = 0;
        // Use algorithm here
    }
}

编辑:删除不正确的返回类型$ P ​​$ pviously简称。 Brainfart。

Removed the incorrect return type previously referred to. Brainfart.

推荐答案

因此​​,基于您的评论你想知道建立一个递归函数的最好方法。你所做的工作,但它是令人费解和略显混乱。我会做的简化是:

So, based on your comment you want to know the best way to set up a recursive function. What you have done will work, but it is convoluted and slightly confusing. What I would do to simplify it is:

void recurse_n(int n) {
    if (n <= 0) {
        // Break-out condition
        return;
    }

    --n;
    recurse_n(n);

    // Your algorithm stuff here.
}

这将使它更容易看到是怎么回事。有一件事我想补充是,虽然你可能想要做的算法东西之前调用recurse_n,但是这一切都取决于你的算法正在做什么。

That will make it easier to see what is going on. One thing I would add though is that you might want to do the algorithm stuff before the call to recurse_n, but that all depends on what your algorithm is doing.

如果你想想看,我写的方式,它会重复,直到n小于或等于0做任何的算法工作之前。这可能是你想要做的算法工作,然后递归。

If you think about it, the way I have written it, it will recurse until n is less than or equal to 0 before doing any of the algorithm work. It might be that you want to do the algorithm work then recurse.

这篇关于以C ++编写一个递归函数的最好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆