简体   繁体   English

在递归 function 中使用来自 main 的数组

[英]Using an array from main in a recursive function

As part of a problem, I need to create a recursive function on a string.作为问题的一部分,我需要在字符串上创建递归 function。
Part of it is based on the nth element of Fibonacci.它的一部分基于斐波那契的第 n 个元素。
The thing is that I need to get n ( the number of elements ) as an input, and only then I can create the array.问题是我需要将 n (元素的数量)作为输入,然后才能创建数组。
But I also need to create a recursive function that has to use the array.但我还需要创建一个必须使用数组的递归 function。
I thought of adding the array to the function as a parameter but I'm not sure if that would decrease the function's efficiency.我想将数组添加到 function 作为参数,但我不确定这是否会降低函数的效率。
So in case it would: Is there any way I can use that specific array in a function in c++?因此,以防万一:有什么方法可以在 c++ 的 function 中使用该特定数组? I calculate the array like this:我这样计算数组:

#include <bits/stdc++.h>
using namespace std;



char IOI(int n,int k) {
    if (n<3) {
        return n;
    }
    if (k<=fibo[n-2]) {
        return IOI(n-2,k);
    }
    else {
        return IOI(n-1,k-fibo[n-2]);
    }

}

int main() {
    int n,k;
    cin >> n >> k;

    int fibo[n+1];
    fibo[0] = 0;
    fibo[1] = 1;
    for (int i = 2; i<n; i++) {
        fibo[i] = fibo[i-1]+fibo[i-2];
    }

    cout << IOI(n,k)


Is there any way I can use that specific array in a function in c++?有什么方法可以在 c++ 的 function 中使用该特定数组?

Yes.是的。 Pass the array as an argument, using some form of indirection.使用某种形式的间接将数组作为参数传递。 Typically, this would be done using a parameter of type span .通常,这将使用span类型的参数来完成。


 cin >> n >> k; int fibo[n+1];

This isn't allowed.这是不允许的。 The size of an array variable must be compile time constant in C++.数组变量的大小必须是 C++ 中的编译时常数。

cin >> n >> k;辛 >> n >> k;
int * fibo = new int[n+1]; int * fibo = new int[n+1];

You can create array dynamically;您可以动态创建数组;

char IOI(int * fibo, int n,int k) { char IOI(int * fibo, int n,int k) {
... ...
} }

And you can add the array as the function parameter.您可以将数组添加为 function 参数。

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

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