返回结果的最有效方法是什么?

时间:2017-04-29 10:19:13

标签: c++ recursion

从递归函数返回布尔/整数值时,我熟悉两种可能的方法,该函数定义了所执行的操作是否成功。

  1. 在递归函数中使用静态变量。更改递归调用中的值,然后在完成所有操作后返回最终值。

  2. 通过引用传递结果变量到递归函数,然后在函数中操作它的值,然后检查值是否与结果相对应。

    void Graph::findPath(string from, string to)
    {
        int result = 0;
        if (from == to) cout<<"There is a path!"<<endl;
        else
        {
            findPathHelper(from, to, result);
            if (result) cout<<"There is a path!"<<endl;
            else cout<<"There is not a path!"<<endl;
        }
    }
    
    
    
    void Graph::findPathHelper(string from, string toFind, int &found)
    {
        for (vector<string>::iterator i = adjList[from].begin(); i != adjList[from].end(); ++i)
        {
            if (!(toFind).compare(*i)) 
                {
                    found = 1;
                    break;
                }
            else
                findPathHelper(*i, toFind, found);
        }
    }
    
  3. 有没有更好的方法来实现这一目标?

    谢谢

2 个答案:

答案 0 :(得分:0)

您可以在递归函数中返回一个值,并使用该返回值检查后续调用中是否成功。

为此目的使用静态变量可能有效,但它通常不是一个好的IDEA,许多人认为它是不好的做法。

查看下面的链接,它解释了为什么我们必须避免静态或全局变量以及它在递归过程中可能导致的问题。

http://www.cs.umd.edu/class/fall2002/cmsc214/Tutorial/recursion2.html

注意:我还没有足够的声誉来发表评论;因此我将此作为答案发布。

答案 1 :(得分:0)

我已将您的实现更改为使用返回值

bool Graph::findPathHelper(const string& from, const string& toFind)
{
    for (vector<string>::iterator i = adjList[from].begin(); i != adjList[from].end(); ++i)
    {
        // I have assumed you comparison was incorrect - i.e. toFind == *i is that you want
        // toFind == *i - The two strings are equal - Thus found
        // or
        // Recurse on *i - Have we found it from recursion
        if (toFind == *i || findPathHelper(*i, toFind))  {
            return true;
        }
    }
    // We have searched everywhere in the recursion and exhausted the list
    // and still have not found it - so return false
    return false;
}
相关问题