std::array vs C-style Arrays
What are the advantages of using std::array over traditional C-style arrays?
std::array is a container provided by the C++ Standard Library that encapsulates a fixed-size array. It provides several advantages over traditional C-style arrays:
- Size and Type Information: With a C-style array, the size and type of the array can decay when passed to a function. This means the function doesn't know the size of the array, which can lead to errors.
std::array, on the other hand, preserves its size and type information. - Bounds Checking:
std::arrayprovides anat()function for accessing elements, which performs bounds checking and throws an exception if the index is out of range. C-style arrays do not have built-in bounds checking. - STL Compatibility:
std::arrayis compatible with the Standard Template Library (STL). This means you can use STL algorithms (likestd::sort,std::find, etc.) directly on astd::array. With C-style arrays, you would need to pass pointers and sizes to these algorithms. - Member Functions:
std::arrayprovides member functions likesize(),empty(),front(),back(), etc., which make it easier to work with the array. C-style arrays don't have these member functions.
Here's an example that illustrates some of these differences:
#include <array>
#include <iostream>
#include <algorithm>
void PrintArray(const std::array<int, 5>& arr) {
std::cout << "Size: " << arr.size() << '\n';
for (int i : arr) {
std::cout << i << ' ';
}
std::cout << '\n';
}
int main() {
std::array<int, 5> MyArray{5, 2, 3, 1, 4};
std::sort(MyArray.begin(), MyArray.end());
PrintArray(MyArray);
}Size: 5
1 2 3 4 5In this example:
- The
PrintArrayfunction knows the size of the array because it's encoded in the type ofarr. - We can directly sort
MyArrayusingstd::sortbecausestd::arrayprovidesbegin()andend()functions.
However, C-style arrays do have one advantage: they can be initialized from string literals, which is not possible with std::array.
Despite this, in most cases, std::array is a safer and more convenient choice than C-style arrays.
Static Arrays using std::array
An introduction to static arrays using std::array - an object that can store a collection of other objects