When I need to store multiple values of same type in c++ I can use a vector or array. So far I have mainly only used vectors, but I have heard that arrays are faster to work with (read and write values). If this is true I would like to know how I could make an array with the size that I read from standard input. I currently use something like this:
int N;
cin >> N;
vector<int> myVector(N);
I have tried:
int N;
cin >> N;
array<int, N> myArray;
but this gives me an error because:
error: the value of 'N' is not usable in a constant expression
I have also tried:
int N;
cin >> N;
int myArray[N];
This will compile, but when I try to ask for the size of this array (myArray.size()) to iterate over it with a for loop then I get an error:
error: request for member 'size' in 'myArray', which is of non-class type 'int [N]'
So should I replace vectors with arrays to make my code faster and if so the how should I do it?
std::array’s speed advantage (and its size limitation for stack-based objects) come from the fact thatstd::arrays size is known at compile-time and it can, thus, avoid allocation and, more importantly, an indirection. There may be a place for anstd::array-like data structure which has a known upper size but a dynamic size up to this upper likit. However, there is no such data structure in the standard C++ library.int myArray[N];is a VLA. This is not legal c++ but a compiler extension. I doubt it is any faster than vector anyways and it makes your code only work on compilers that support this non standard extension.