How do I construct and use std::array in C++?

In C++, std::array is a container that encapsulates fixed size arrays. It is a part of the Standard Template Library (STL) and provides a way to work with arrays in a more convenient and safer way compared to traditional C-style arrays. Here’s how you can construct and use std::array:

Constructing std::array

You can initialize a std::array by specifying its size and type as follows:

#include <array> #include <iostream> int main() { // Initialize a std::array of size 5 std::array numbers = {1, 2, 3, 4, 5}; // Access elements using the array subscript operator for (size_t i = 0; i < numbers.size(); ++i) { std::cout << numbers[i] << " "; } std::cout << std::endl; return 0; }

Using std::array

Once you have constructed a std::array, you can use a variety of member functions to interact with it, such as:

  • at() - Access an element with bounds checking.
  • front() - Access the first element.
  • back() - Access the last element.
  • begin() and end() - Provide iterators for the array.

std::array C++ STL fixed size array container C++ array example