Print contents of an array in reverse order in C++

In this post, we will see how to print contents of an array in reverse order in C++.

 

1. Using Array Indices

Naive solution would be to loop through the elements of the array and print each element.

 

Download   Run Code

Output:

40 30 20 10

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

 

Download   Run Code

Output:

40 30 20 10

 

2. std::copy

Another good alternative is to use output iterator std::ostream_iterator to print array contents to the output stream std::cout. It can be done with the help of std::copy which takes reverse iterator to the starting and ending positions of the array and the output iterator.

 

Download   Run Code

Output:

40 30 20 10

 
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 << operator, separated by a delimiter between every two elements.

 

Run Code

Output:

5 4 3 2 1

 

3. C++11 - Iterators

We can get iterators to the array with the help of std::cbegin and std::cend which are introduced in C++11. The idea is to start a loop from std::cend which returns a constant iterator to the end of the array. Then we iterate backwards and print each element till we reach std::start which returns a constant iterator to the beginning of the array.

 

Download   Run Code

Output:

40 30 20 10

 

4. std::for_each

We can also use std::for_each that takes an input range defined by two iterators and applies a function on every element of that range. The function can be a unary function, or an object of a class overloading the ()operator or a lambda expression.

Function

Download   Run Code

Class

Download   Run Code

Lambda

Download   Run Code

Output:

5 4 3 2 1

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of