Implementing Fixed-Size Arrays with C++ std::array
The std::array container, introduced in C++11, provides a safer and more feature-rich alternative to traditional C-style arrays with out sacrificing performance. Unlike dynamic containers, std::array maintains a fixed size determined at compile time, preventing runtime resizing.
This container is defined as a class template in the <array> header within the std namespace:
namespace std {
template <typename ElementType, size_t ArraySize>
class array;
}
To use std::array, include the header and utilize the namespace:
#include <array>
using namespace std;
The template parameters specify the element type and container size, where ArraySize must be a constant expression. Here's how to create an array of 10 double-precision numbers:
std::array<double, 10> numberList;
This declaration creates uninitialized elements. To zero-initialize all elements:
std::array<double, 10> numberList{};
Explicit initialization supports partial element specification:
std::array<double, 10> numberList{0.5, 1.0, 1.5, 2.0};
Unspecified elements default to zero. The container offers several member functions for element access and manipulation:
| Functtion | Purpose |
|---|---|
begin() |
Returns iterator to first element |
end() |
Returns iterator to position after last element |
size() |
Returns number of elements (always equals ArraySize) |
empty() |
Checks if container is empty |
at(pos) |
Returns reference to element at pos with bounds checking |
front() |
Returns reference to first element |
back() |
Returns reference to last element |
data() |
Returns pointer to underlying array |
swap(other) |
Exchanges contents with another array of identical type and size |
Global functions std::begin() and std::end() work with both containers and raw arrays. The std::get() function template provides indexed element access.
Example implementation:
#include <iostream>
#include <array>
using namespace std;
int main() {
array<int, 4> data{};
for (size_t index = 0; index < data.size(); ++index) {
data.at(index) = index;
}
cout << get<3>(data) << endl;
if (!data.empty()) {
for (auto iterator = data.begin(); iterator != data.end(); ++iterator) {
cout << *iterator << " ";
}
}
return 0;
}
Output:
3
0 1 2 3