跟踪在C++中调用递归函数的次数

bac*_*i32 7 c++ recursion global-variables

我正在尝试使用一个函数,该函数的参数是一个字符串向量.我想对该函数使用递归,但每次调用该函数时,我都想更改参数,例如

fun(stringArray[i]) 
Run Code Online (Sandbox Code Playgroud)

其中i是调用函数的时间.

所以更简单的方式就像跟随.但我需要跟踪功能乐趣的执行次数.

void fun(){
    cout<<hi;
    if(x!=10)
    fun()
}

int main(){

    fun();
}
Run Code Online (Sandbox Code Playgroud)

在这一个让我们说我想打印出来只有10次,所以想要有一个增量的变量,当达到10时,它会停止.所以一般来说我该怎么做才能跟踪呢?我尝试使用全局变量,但它们似乎不适用于函数.有什么建议?

Nic*_*tti 11

我在这里看到了很多混乱,所以我决定把事情搞清楚.

解决方案0:静态变量

考虑使用轻微修改提出的代码

#include<iostream>
using namespace std;

void fun()
{
    static int count=1;
    count++;
    cout << "fun() is called " << count << " times" << endl;
    if(count<=10)
    {
            fun();
    }
}

int main()
{
    cout << "first call" << endl;
    fun();
    cout << "second call" << endl;
    fun();
    cout << "third call" << endl;
    fun();
}
Run Code Online (Sandbox Code Playgroud)

这是输出:

first call
fun() is called 2 times
fun() is called 3 times
fun() is called 4 times
fun() is called 5 times
fun() is called 6 times
fun() is called 7 times
fun() is called 8 times
fun() is called 9 times
fun() is called 10 times
fun() is called 11 times
second call
fun() is called 12 times
third call
fun() is called 13 times
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,静态变量的使用可能会导致一些可怕的错误.

在这里你有一个单击功能,将来会给你带来一些巨大的痛苦.

此外,静态变量的使用导致不可读的代码容易出错

就是不要这样做!

解决方案1:按值传递的变量

考虑以下代码:

#include <iostream>
using namespace std;

void fun(int i){
    cout<<i<<endl;
    if(i!=3) {
        i++;
        fun(i);
        fun(i);
    }
}

int main(){
    fun(0);
}
Run Code Online (Sandbox Code Playgroud)

这是输出:

0
1
2
3
3
2
3
3
1
2
3
3
2
3
3
Run Code Online (Sandbox Code Playgroud)

如您所见,输出不是调用函数的次数

解决方案2:通过引用传递的变量

#include <iostream>
using namespace std;

void fun(int& x){
    if(x>=10)
        return;
    ++x;
    cout << x << endl;
    fun(x);
}

void funEntry(){
    int x = 0;
    cout << "Entry point" << endl;
    fun(x);
}

int main(){
    funEntry();
    funEntry();
}
Run Code Online (Sandbox Code Playgroud)

将打印

Entry point
1
2
3
4
5
6
7
8
9
10
Run Code Online (Sandbox Code Playgroud)

这种方法也适用于像这样一些更奇特的递归模式

#include <iostream>
using namespace std;

void fun(int i, int& x){
    if(i>=4)
        return;
    ++x;
    cout << i << " " << x << endl;
    fun(i+1,x);
    fun(i+2,x);
}

void funEntry(){
    int x = 0;
    cout << "Entry point" << endl;
    fun(0,x);
}

int main(){
    funEntry();
    funEntry();
}
Run Code Online (Sandbox Code Playgroud)

输出:

Entry point
0 1
1 2
2 3
3 4
3 5
2 6
3 7
Entry point
0 1
1 2
2 3
3 4
3 5
2 6
3 7
Run Code Online (Sandbox Code Playgroud)