std::array

std::array is an STL container that wraps around a fixed size array. It stores items contiguously in memory. In modern C++, it should be used in place of a raw array.

To use std::array, we need to include the array header:

#include <array>

std:array<int, 5> int_array1; // Will contain junk by default
std::array<int, 5> int_array2 {}; // Will contain all zeros
std::array<int, 5> int_array3 {1, 2, 3}; // Will contain 1,2,3,0,0
std::array int_array4 {10, 12, 5, 17, 20}; //Compiler will deduce <int, 5>

Some common methods of the array type are at, which gets or sets the value at the specified index, size, which returns how many items are in the array, front, which returns the first value, and back which returns the last value. There is also the [] operator for setting and getting values. The difference with at is that at does range checking and throws an exception if we are outside the bounds. We can get access to the underlying array by using the data method in case we need to pass the raw array to a function or method.

Read more about std::array.

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.