Kartik Sibal
Kartik Sibal

Reputation: 51

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++?

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?

Upvotes: 2

Views: 252

Answers (2)

Humam Helfawi
Humam Helfawi

Reputation: 20311

If you want a static array(const number of items), use std::array:

std::array<int,50> a;

If you want a dynamic array(non const number of array), use 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:

a.resize(100);

or just by pushing new items:

a.push_back(5);

read more about std::vector. It can serve you more than you can imagine.

P.S. the second code of your question is not valid (or at least it is not standard). However, you can do this instead:

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

Upvotes: 9

Daniel
Daniel

Reputation: 8451

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;

Upvotes: 2

Related Questions