Arrays#
reading
Arrays have many similarities to vectors. In particular, both arrays and vectors store the data contiguously in memory. This means you get good cache performance when looping over elements.
But there are some key differences:
Vectors can grow in size as needed to accommodate additional data. In contrast, arrays are fixed-size.
Arrays also are allocated in a different part of memory by default (the stack rather than the heap—more on this later).
Arrays do not initialize their elements by default when declared.
Important
Because arrays are fixed-size, you need to specify the size at compile time.
std::array#
Here’s a simple example:
#include <iostream>
#include <array>
int main() {
std::array<int, 10> int_arr{};
for (auto e : int_arr) {
std::cout << e << std::endl;
}
}
Declaring the array takes 2 arguments in the <>—the datatype and the number of elements.
Notice that when we look over the elements, they are uninitialized.
We can use an initializer list to give initial values, like:
std::array<int, 10> int_arr{0};
If you don’t give all the values, the remainder are initialized to 0:
try it…
What are the values from this:
std::array<int, 10> int_arr{1, 2};
Looping over array elements#
Looping over the elements of an array works the same as with vectors,
and likewise we can get the size via the .size() member function:
#include <array>
#include <iostream>
int main() {
std::array<int, 10> arr{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
std::cout << "size of array is " << arr.size() << std::endl;
for (auto e : arr) {
std::cout << e << std::endl;
}
}
Older style arrays#
Caution
In C and older C++, you will see fixed-side arrays declared as:
double x[10];
The std::array is a more modern wrapper for this—it has the
advantage that it knows the size of the array and works with
our loops and the algorithms provided by the C++ standard library.