可以从命令行参数读取std :: array的维数吗? [英] Can the dimension of std::array be read from command line arguments?
问题描述
我有一个C ++代码,我决定使用 std :: array
而不是 std :: vector
,我希望从命令中读取数组的大小线.
I have a C++ code where I decided to use std::array
instead of std::vector
and I want the size of the array to be read from command line.
在实践中,可以使用以下代码段进行总结
In practice, this can be summarized with the following snippet
#include <iostream>
#include <array>
#include <sstream>
int main(int argc, char* argv[]){
std::size_t my_size;
{
std::istringstream is{argv[1]};
is >> my_size;
}
std::cout << my_size<<std::endl;
std::array<int,my_size> a;
return 0;
}
编译器会给出以下错误,这是由于必须在编译时知道 my_size
的事实.
The compiler gives the following error, which is due to the fact that my_size
must be known at compile time.
错误:常量表达式中无法使用"my_size"的值
14 |std :: array< int,my_size>一个;
error: the value of ‘my_size’ is not usable in a constant expression
14 | std::array<int,my_size> a;
有什么方法可以让 std :: array
的大小从命令行给出?还是我绝对应该使用其他容器?作为堆上的动态数组或 std :: vector
?
Is there any way to let the size of an std::array
to be given from command line? Or should I definitely use other containers? As dynamic arrays on the heap, or std::vector
?
推荐答案
在编译时必须特别知道类型和数组的大小,因此答案是:否.
Types and arrays sizes in particular must be known at compile time, hence the answer is: No.
您可以实现从运行时值到编译时常量的某些映射.
You can implement some mapping from a runtime value to a compile-time constant. Something along the line of
size_t size;
std::cin >> size;
if (size == 10) {
std::array<int,10> x;
// use x
} else if (size == 20) [
std::array<int,20> y;
// use y
}
但是,这用途非常有限,因为 x
和 y
是不同类型的.如果仅在运行时知道大小,则使用 std :: vector
会更容易.
However, this is of very limited use, because x
and y
are of different type. When the size is only known at runtime it is easier to use a std::vector
.
这篇关于可以从命令行参数读取std :: array的维数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!