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:
std::array
, on the other hand, preserves its size and type information.std::array
provides an at()
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.std::array
is compatible with the Standard Template Library (STL). This means you can use STL algorithms (like std::sort
, std::find
, etc.) directly on a std::array
. With C-style arrays, you would need to pass pointers and sizes to these algorithms.std::array
provides member functions like size()
, 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 5
In this example:
PrintArray
function knows the size of the array because it's encoded in the type of arr
.MyArray
using std::sort
because std::array
provides begin()
and end()
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.
Answers to questions are automatically generated and may not have been reviewed.
std::array
An introduction to static arrays using std::array
- an object that can store a collection of other objects