![](/img/trans.png)
[英]Is there a way to define array size based on command line argument? Run time vs compile time instantiation?
[英]Instantiation of array class of size unknown at compile time
下面是一个小脚本,用于打印数字 1 到 n 的总和,因为 n = 1,...,20。
#include <iostream>
#include <array>
using namespace std;
int test(int n)
{
array<int,n> myArray;
for (int iii = 0; iii < n; iii++)
myArray[iii] = iii+1;
int nSum;
for (int iii = 0; iii < n; iii++)
nSum += myArray[iii];
return nSum;
}
int main()
{
for (int n = 1; n <= 20; n++)
cout << test(n) << endl;
return 0;
}
当然,这不会编译:
Main.cpp: In function ‘int test(long unsigned int)’:
Main.cpp:9:13: error: ‘n’ is not a constant expression
array<int,n> myArray;
^
Main.cpp:9:13: note: in template argument for type ‘long unsigned int’
Main.cpp:9:22: error: invalid type in declaration before ‘;’ token
array<int,n> myArray;
^
Main.cpp:11:26: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
for (int iii = 0; iii < n; iii++)
^
Main.cpp:12:14: error: invalid types ‘int[int]’ for array subscript
myArray[iii] = iii+1;
^
Main.cpp:16:26: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
for (int iii = 0; iii < n; iii++)
^
Main.cpp:17:22: error: invalid types ‘int[int]’ for array subscript
nSum += myArray[iii];
^
make: *** [Main.o] Error 1
问题似乎是(除其他外) n
不是一个常量表达式,我明白为什么这是一个问题,但我不知道如何解决它。
我知道如何使用新函数实例化“常规”数组,但我不明白如何使用数组类。
如何让test
函数将n
视为常量?
您基本上有两种选择。
正如您已经提到的, std::array
需要一个编译时大小。 所以在编译时让它知道! 这可以通过将其转换为模板参数来完成。
改变
int test(int n) { . . . }
到
template<int n> int test() { . . . }
问题是它然后必须用test<n>()
而不是test(n)
来调用,这又要求调用者代码中的n
在编译时也是已知的,这不是for
循环。 如果您在编译时知道循环的上限(例如在您当前的代码片段中),则可以完成,但有点复杂。 如果它是未知的,即用户输入,则根本无法使用此解决方案。
所以这在这里不是一个好的选择。
不要使用std::array
而是一种容器类型,它在编译时不需要大小,但在运行时。 正如您所提到的,堆分配的原始数组( new int[n]
)是一种选择,但它不是很 C++-ish。 改用std::vector
!
为此,只需更改
array<int,n> myArray;
到
vector<int> myArray(n);
附注。 将来,可能会出现std::dynarray
(提议的容器类型) ,它比目前的std::vector
更适合该目的。 它反映了new int[n]
的目的,其中n
在运行时已知,但在数组的生命周期内保持不变,填补了std::array
和std::vector
之间的空白。 然而在几乎所有情况下std::vector
都可以正常工作!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.