如何在函数参数中通过引用获取数组?

时间:2017-06-16 03:47:26

标签: c++

如果数据类型是typedef,如何通过引用传递数组。我正在学习c ++,我阅读了call-by-reference的概念,但是当我按照那个实现时 - 我收到了一个错误(在代码之后粘贴在下面)。请问,任何人都可以解释发送数组作为参考调用的最佳方式吗?

#include <iostream>
#include <vector>
using namespace std;

typedef unsigned long ulong;

ulong fib_dynamic(ulong n, ulong &memo[]){
  if(n < 2) return 1;
  if(memo[n] == 0){
    memo[n] = fib_dynamic(n-1, memo) + fib_dynamic(n-2, memo);
  }
  return memo[n];
}

ulong fib_iterative(ulong n){
  ulong fib[n+1];
  fib[0] = 1;
  fib[1] = 1;
  for(int i=2; i<n; i++) {
    fib[i] = fib[i-1] + fib[i-2];
  }
  return fib[n-1];
}

int main(){

  ulong n;
  cout << "Welcome to Fib Calculator\nEnter the n:";
  cin >> n;
  ulong memo[n];

  cout << endl << n << " th fib num(dynamic) = " << fib_dynamic(n,memo) << endl;
}

//错误

1-fib-dp.cpp:13:47: error: 'memo' declared as array of references of type
      'unsigned long &'
ulong fib_dynamic(ulong n, unsigned long &memo[]){
                                              ^
1-fib-dp.cpp:37:53: error: no matching function for call to 'fib_dynamic'
  cout << endl << n << " th fib num(dynamic) = " << fib_dynamic(n,memo) << endl;
                                                    ^~~~~~~~~~~
1-fib-dp.cpp:13:7: note: candidate function not viable: no known conversion from
      'ulong [n]' to 'int' for 2nd argument
ulong fib_dynamic(ulong n, unsigned long &memo[]){
      ^
2 errors generated.

2 个答案:

答案 0 :(得分:5)

使用std::vector,因为在这种情况下,您需要一个动态大小的数组(即数组的大小是在运行时决定的)。通过引用传递向量,小心不要越界

#include <iostream>
#include <vector>
using namespace std;

ulong fib_dynamic(ulong n, std::vector<unsigned long>& memo){
    if(n < 2) return 1;
    if(memo[n] == 0){
        memo[n] = fib_dynamic(n-1, memo) + fib_dynamic(n-2, memo);
    }
    return memo[n];
}

int main() {

    ulong n;
    cout << "Welcome to Fib Calculator\nEnter the n:";
    cin >> n;
    std::vector<unsigned long> memo(n + 1);

    cout << endl << n << " th fib num(dynamic) = " << fib_dynamic(n,memo)
         << endl;
}

答案 1 :(得分:1)

数组默认通过指针传递。 阅读thisthis

代码 -

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

typedef unsigned long ulong;


ulong fib_dynamic(ulong n, ulong (*memo)){
  if(n < 2) return 1;
  if(memo[n]!=0)return memo[n];
  if(memo[n] == 0){
    memo[n] = fib_dynamic(n-1, memo) + fib_dynamic(n-2, memo);
  }
  return memo[n];
}

ulong fib_iterative(ulong n){
  ulong fib[n+1];
  fib[0] = 1;
  fib[1] = 1;
  for(ulong i=2; i<n; i++) {
    fib[i] = fib[i-1] + fib[i-2];
  }
  return fib[n-1];
}

int main(){
  ulong n;
  cout << "Welcome to Fib Calculator\nEnter the n:";
  cin >> n;
  ulong memo[n+1];
  memset(memo,0,sizeof memo);
  memo[0]=memo[1]=1;
  cout << endl << n << " th fib num(dynamic) = " << fib_dynamic(n,memo) << endl;
}

我做了一些修改,因为它没有正常工作。