引用在运行时确定的大小数组

yu *_*uan 4 c++ arrays reference variable-length-array

我试图找到这个,但找不到任何.我知道我可以创建一个数组变量的引用:

int x[10] = {}; int (&y)[10] = x;
Run Code Online (Sandbox Code Playgroud)

但是,在编译时不知道数组大小的情况下,如下面的代码所示:

const int n = atoi( string ); //the string is read from a text file at run time.
int x[n] = {}; int (&y)[n] = x; //this generates a compiling error.
Run Code Online (Sandbox Code Playgroud)

即使int n被声明为const,只要在编译时不知道n,引用就是无效的.编译器会这样说:类型'int [n]'的引用不能绑定到不相关类型'int [n]'的值.任何人都知道如何解决这个问题?提前致谢.

Bri*_*ian 6

运行时长度数组是C99功能,在标准C++中不存在.它们作为某些C++编译器的扩展而存在,但不能与C++特性(如引用和模板)很好地混合使用.

你应该使用矢量.