简体   繁体   English

在C ++中声明数组的最佳方法是什么?

[英]What is the best way to declare an array in C++?

I was curious as to what will be a better way to initalise an array in C++? 我很好奇在C ++中使用数组的更好方法是什么?

Will it be: 那将会:

int array[50];

or 要么

int x;

cin>> x; //Input a number to initialise the array.

int array[x];

Which of these two will be a better option to initialise an array and why? 这两个中的哪一个是初始化数组的更好选择,为什么? If none, then is there a third way? 如果没有,那么还有第三种方式吗?

If you want a static array(const number of items), use std::array : 如果你想要一个静态数组(const项数),使用std::array

std::array<int,50> a;

If you want a dynamic array(non const number of array), use std::vector : 如果你想要一个动态数组(非常数的数组),请使用std::vector

std::vector<int> a(50);

in this case you can change the size of the vector any time you want by resizing it: 在这种情况下,您可以通过resizing大小来随时更改向量的resizing

a.resize(100);

or just by pushing new items: 或者只是推新物品:

a.push_back(5);

read more about std::vector . 阅读更多关于std::vector It can serve you more than you can imagine. 它可以为您提供超出您想象的服务。

PS the second code of your question is not valid (or at least it is not standard). PS你的问题的第二个代码是无效的(或至少它不是标准的)。 However, you can do this instead: 但是,您可以这样做:

int x;
cin>> x; //Input a number to initialise the array.
std::vector<int> array(x);

If you know the size of an array at compile time, and it will not change, then the best way is: 如果你在编译时知道数组的大小,并且它不会改变,那么最好的方法是:

std::array<int, 50> arr;

Otherwise use 否则使用

std::vector<int> arr;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM