C++ 11 – std::array
When you need an array in C++, below is a simple way you can do that. This is a C-style array.
int normal_array[5] = {1, 2, 3, 4, 5};
To traverse it, you would use a for loop where you need to hardcode the size. And then also write all the code for operations on it by yourself. And while accessing any array element, even if the bounds are crossed, it would compile well.
for (int i = 0; i < 5; ++i) {
C++ 11 introduced std::array in STL just like we have std::vector and other STLs. The two operations discussed above for the regular array will transform as below for C++ 11 std::array.
#include <array>
std::array<int, 5> my_array = {1, 2, 3, 4, 5};
for (int i = 0; i < my_array.size(); ++i) {
Features and advantages of std::array
The main features and advantages of the std::array feature are listed below.
The array size is fixed at compile-time itself. It cannot be resized at run time.
std::array<int, 5> my_array; // Creates an array of 5 integers
The program checks the bounds while accessing an element. Errors such as std::out_of_range are caught while using std::array. This feature is not possible in a C-style array.
try {
// This will throw an exception
int value = my_array.at(10);
} catch (const std::out_of_range& e) {
std::cout << "Out of range: " << e.what() << std::endl;
}
Here, my_array is std::array type variable. It is a template class internally and has a data function that provides access to the actual data. You can use the data algorithm on the std::array to get the pointer to the array.
int* ptr = my_array.data();
Standard functions such as size(), empty(), begin(), end(), rbegin(), rend(), front() and back() are available on std::array like other STLs.
// Get the size of the array
size_t array_size = my_array.size();
Memory allocation for std::array is on the stack or automatic storage, unlike dynamic vectors, and hence has greater performance compared to vectors.
std::array<int, 5> my_array;
C++ 11 introduced uniform initialization using braces. std::array complies with that feature, as shown.
std::array<int, 5> my_array = {1, 2, 3, 4, 5};
std::array can be used in range-based for loops and initializer lists.
for (const auto& element : my_array) {
std::cout << element << " ";
}
std::cout << std::endl;
Concluding, std::array has the advantages of a C-style array, such as fixed-size memory management and static allocation. In addition, it supports type-safe, error-free array implementation and has more features similar to other STLs.