如果数据类型是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;
}
Run Code Online (Sandbox Code Playgroud)
//错误
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.
Run Code Online (Sandbox Code Playgroud)
使用a,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;
}
Run Code Online (Sandbox Code Playgroud)