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?

3
  • 7
    In general, the better way is to use std::vector instead. Commented Feb 5, 2016 at 8:09
  • 5
    The first is valid C++, the second isn't. So the first one is the best out of the two. Commented Feb 5, 2016 at 8:10
  • Neither initialises the array. int array[50] = {0}; would be the best way to initialise it, if you really need an array. Commented Feb 5, 2016 at 8:15

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

6 Comments

What if i declare namespace stds before main? How will this work in that case?
you mean using namespace std; ??
Yes. I am a newbie so. :-)
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 .
It'd be lovely if you could elaborate as to why it isn't a good practise.
|
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;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.