Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C++ Array::rend() Function



The C++ std::array::rend() function is used to return a reverse iterator pointing to the element previous to the first element of the array used in reverse traversal.

This iterator moves from the last element toeards the beginning. Unlike regular iterator, it starts at the end and works backwards.

Syntax

Following is the syntax for std::array::rend() function.

reverse_iterator rend() noexcept;
const_reverse_iterator rend() const noexcept;

Parameters

It does not accepts any parameter.

Return Value

This function returns a reverse iterator to the reverse end of the sequence.

Exceptions

This function never throws exception.

Time complexity

Constant i.e. O(1)

Example 1

In the following example, we are going to consider the basic usage of rend() function.

#include <iostream>
#include <array>
int main() {
   std::array < int, 4 > a = {12,23,34,45};
   for (auto x = a.rbegin(); x != a.rend(); ++x) {
      std::cout << * x << " ";
   }
   return 0;
}

Output

Output of the above code is as follows −

45 34 23 12

Example 2

Consider the following example, where we are going to use rend() function to compare two arrays in reverse order.

#include <iostream>
#include <array>
int main() {
   std::array < int, 3 > x = {11,22,33};
   std::array < int, 3 > y = {11,22,33};
   if (std::equal(x.rbegin(), x.rend(), y.rbegin())) {
      std::cout << "Arrays are equal" << std::endl;
   } else {
      std::cout << "Arrays are not equal" << std::endl;
   }
   return 0;
}

Output

Following is the output of the above code −

Arrays are equal

Example 3

Let's look at the following example, where we are going to use rend() function to traverse and modify each element.

#include <iostream>
#include <array>
int main() {
   std::array < int, 3 > x = {12,23,34};
   for (auto a = x.rbegin(); a != x.rend(); ++a) {
      * a *= 2;
   }
   for (const auto & num: x) {
      std::cout << num << " ";
   }
   return 0;
}

Output

If we run the above code it will generate the following output −

24 46 68 
array.htm
Advertisements