std::array<> is introduced in c++11 and it’s a wrapper around old C style array, with added advantages.
It’s is a kind of sequential container with constant size elements.

std::array is internally defined as class template i.e.

Here first template parameter T is the type of elements to be stored in array and 2nd template parameter i.e.
size_t N is a constant that represents the number of elements in array.

Header File required for std::array i.e.

Defining and Initializing an std::array<> object

Here, std::array object arr represents an int array of fixed size 10 and its uninitialized, hence all 10 elements contains garbage value.

Here, std::array object arr1 represents an string array of fixed size 200.

If we provide less number of elements during initialization, remaining will be initialized with default value. Like in case of int its 0. So, arr3 contains,

std::array also provides a member function fill() to set the same value for all elements in one go. Its easy when we have large array.

So, arr4 contains,

Complete example is as follows,

Output:

How to get the size of std::array

Size of a std::array object is always constant i.e. its 2nd template parameter. However, std::array provides a member function size() to return the size i.e.

How to access elements in std::array

There are 3 ways to access elements in std::array

operator []: Accessing element in std::array using operator []

Accessing out of range elements using [] operator will lead to undefined behaviour.

at() : Accessing element in std::array using at() member function

Accessing any out of range element using at() function will throw out_of_range exception.

std::tuple’s get<>()

Accessing out of range elements using get<> operator will give compile time error.

Complete example is as follows,

Output:

How to Iterate over a std::array<> object

In the below example we will see 4 different ways to iterate over an array

  • Iterate using Range based for loop
  • Iterate using for loop
  • Iterate using Iterator
  • Iterate using for_each

Complete example is as follows,

Output:

 

 

Click Here to Subscribe for more Articles / Tutorials like this.