C++ Deque::rend() Function



The C++ std::deque::rend() function is used to return the reverse iterator pointing to the element preceding the first element of the deque. This iterator is used in reverse iteration over the deque, typically in combination with rbegin(), which points to the last element. By iterating from rbegin() to rend(), you can access all the elements in reverse sequence.

Syntax

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

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

Parameters

It does not accept any parameter.

Return value

It returns a reverse iterator to the reverse end of the sequence container.

Exceptions

This function never throws exception.

Time complexity

The time complexity of this function is Constant i.e. O(1)

Example

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

#include <iostream>
#include <deque>
int main()
{
    std::deque<char> a = {'A', 'B', 'C', 'D'};
    for (auto x = a.rbegin(); x != a.rend(); ++x) {
        std::cout << *x << " ";
    }
    return 0;
}

Output

Output of the above code is as follows −

D C B A 

Example

Consider the following example, where we are going to modify the deque in the reverse order.

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

Output

Following is the output of the above code −

Modified deque: 3 36 69 102
deque.htm
Advertisements