C++ <array> - rend() Function
The C++ array::rend function returns the reverse iterator pointing to the element preceding the first element (reversed past-the-last element) of the array. A reverse iterator iterates in backward direction and increasing it results into moving to the beginning of the array container. Similarly, decreasing a reverse iterator results into moving to the end of the array container.
Syntax
reverse_iterator rend() noexcept; const_reverse_iterator rend() const noexcept;
Parameters
No parameter is required.
Return Value
A reverse iterator to the reversed past-the-last element of the sequence container. If the sequence object is constant qualified, the function returns a const_reverse_iterator, else returns an reverse_iterator.
Time Complexity
Constant i.e, Θ(1).
Example:
In the example below, the array::rend function returns the reverse iterator pointing to the element preceding the first element of the array MyArray.
#include <iostream> #include <array> using namespace std; int main (){ array<string, 3> MyArray{"Alpha","Coding","Skills"}; array<string, 3>::reverse_iterator rit; rit = MyArray.rend(); rit--; cout<<*rit<<" "; rit--; cout<<*rit<<" "; rit--; cout<<*rit<<" "; return 0; }
The output of the above code will be:
Alpha Coding Skills
Example:
Lets see another example where the array called MyArray contains integer values and array::rend function is used with array::rbegin function to specify a range including all elements of the array container.
#include <iostream> #include <array> using namespace std; int main (){ array<int, 5> MyArray{10, 20, 30, 40, 50}; array<int, 5>::reverse_iterator rit; for(rit = MyArray.rbegin(); rit != MyArray.rend(); ++rit) cout<<*rit<<" "; return 0; }
The output of the above code will be:
50 40 30 20 10
❮ C++ <array> Library