11.5. The std::array class¶
The std::array is a container that encapsulates fixed size arrays.
Since it is literally a wrapper around a raw array,
the size of a std::array must be defined when declared.
std::array <int, 12> days_per_month;
The array class is very lightweight and has very little
costs over a raw array.
Additionally, std::array provides convenience functions such as:
- at() and operator[]
range checked access and unchecked access
- front() and back()
access to the first and last elements
- size()
return the number of elements
- empty()
check if the container is empty
Unlike a raw array, std::array cannot infer its size if
declared with an initializer list:
1#include <array>
2#include <iostream>
3using std::cout;
4
5int main() {
6 // compile error: array template parameter missing:
7 //std::array<char> letters = {{'h', 'o', 'w', 'd', 'y', '!'}};
8
9 std::array<char, 6> letters = {{'h', 'o', 'w', 'd', 'y', '!'}};
10
11 cout << "The first character is: " << letters.front() << '\n';
12 cout << "The last character is: " << letters.back() << '\n';
13
14 for (const auto& c: letters) {
15 cout << c;
16 }
17}
11.5.1. Container class member type aliases¶
All the standard library containers, including std::array, provide a
large set of member types. Standard-library types publish aliases so generic
code can ask a container, "What type of elements, sizes, references, and
iterators do you use?" without knowing its implementation.
For a particular std::array<T, N>, several answers may seem self-evident:
its size_type is std::size_t, its pointer is T*, and its
reference is T&. A generic function, however, might be given an
array, a vector, a list, or a user-defined container. It should use
Container::size_type rather than assume that every container chose
std::size_t. The alias is part of the container's public contract, and it
keeps generic code independent of that choice.
The most commonly used std::array aliases are:
value_type: the element type,T.size_type: the unsigned type used for sizes and indexes,std::size_t.difference_type: the signed type used for iterator distances,std::ptrdiff_t. For a random-access container such as an array,end() - begin()has this type. It is signed because reversing the order of the operands can produce a negative distance.referenceandconst_reference:T&andconst T&, the types produced by dereferencing a mutable or const iterator.pointerandconst_pointer:T*andconst T*.iteratorandconst_iterator: the types returned bybegin()andend(). They allow standard algorithms to traverse the container without knowing how it stores its elements.
std::array also provides reverse-iterator aliases. We will examine the
requirements of iterator types, and how to implement an iterator class, in the
list chapter.
More to Explore