2

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?

2 Answers2

9

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);
Humam Helfawi
  • 19,566
  • 15
  • 85
  • 160
  • What if i declare namespace stds before main? How will this work in that case? – Kartik Sibal Feb 05 '16 at 08:15
  • you mean using namespace std; ?? – Humam Helfawi Feb 05 '16 at 08:15
  • Yes. I am a newbie so. :-) – Kartik Sibal Feb 05 '16 at 08:20
  • it is not best practise to using the whole std namespace just write it in front of every thing you would use like std::vector... std::array ... std::sort ... but if there is something you will use a lot like std::begin for example then just use it : using std::begin. and try to make inside a specific method . – Humam Helfawi Feb 05 '16 at 08:22
  • It'd be lovely if you could elaborate as to why it isn't a good practise. – Kartik Sibal Feb 05 '16 at 08:23
  • you will end up with a lot of mess. However, good practise is something opinion-based so you do not have to follow it (although sth like this I would take it as mandatory). However, read this please http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice – Humam Helfawi Feb 05 '16 at 08:25
2

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;
Daniel
  • 8,179
  • 6
  • 31
  • 56