This post will discuss how to print the contents of an array in C++.

1. Using Array Indices

A simple solution is to iterate over the elements of an array and print each element.

Download  Run Code

Output:

1 2 3 4 5

 
The above code uses the sizeof operator for determining the array size. We can also create a template that deduces the size of the array from its declared type.

Download  Run Code

Output:

1 2 3 4 5

2. Using std::copy with std::ostream_iterator function

We can use Ostream iterators to write to an output stream. The idea is to use an output iterator std::ostream_iterator to print array contents to std::cout with the help of std::copy, which takes input iterator to the starting and ending positions of the array and the output iterator.

Download  Run Code

Output:

1 2 3 4 5

 
With C++17, we can use std::copy with std::experimental::ostream_joiner which is defined in header <experimental/iterator>. It is a single-pass output iterator which can write successive array elements into the std::cout, using the << operator, separated by a delimiter between every two elements.

Run Code

Output:

1 2 3 4 5

3. Using range-based for-loop

Starting C++11, the recommended approach is to use a range-based for-loop, as shown below:

Download  Run Code

Output:

1 2 3 4 5

4. Using Iterators

We can even use iterators to print array contents even though the array is not an STL container. The idea is to use the std::begin and std::end introduced in C++11. std::start returns an iterator to the beginning and std::end returns an iterator to one past the end of the given array. Since we’re not modifying anything, we should use std::cbegin and std::cend, which returns constant iterators.

Download  Run Code

Output:

1 2 3 4 5

5. Using std::for_each function

Another good alternative is to use the std::for_each algorithm, which applies the specified function on every element within the specified range defined by two iterators. The function can also be an object of a class overloading the ()operator or a lambda expression.

Function


Download  Run Code

Output:

1 2 3 4 5

Class


Download  Run Code

Output:

1 2 3 4 5

Lambda


Download  Run Code

Output:

1 2 3 4 5

That’s all about printing the contents of an array in C++.