C++ Deque::rbegin() Function



The C++ std::deque::rbegin()function is used to return the reverse iterator pointing to the last element of the deque. It allows for reverse traversal of the deque, starting from the end and moving towards the beginning. It is typically used in conjunction with the rend() function, which points to the preceding first element.

Syntax

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

reverse_iterator rbegin() noexcept;
const_reverse_iterator rbegin() const noexcept;

Parameters

It does not accepts any parameter.

Return value

It returns the reverse iterator pointing to the last element of the deque.

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 rbegin() 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 += 2;
    }
    std::cout << "Modified elements: ";
    for (int val : a) {
        std::cout << val << " ";
    }
    return 0;
}

Output

Following is the output of the above code −

Modified elements: 3 14 25 36 

Example

Let's look at the following example, where we are going to check whether the deque is palindrome or not.

#include <iostream>
#include <deque>
bool isPalindrome(const std::deque<char>& a)
{
    return std::equal(a.begin(), a.end(), a.rbegin());
}
int main()
{
    std::deque<char> x = {'A', 'B', 'C', 'B', 'A'};
    std::deque<char> y = {'A', 'B', 'C'};
    std::cout << "x is palindrome: " << (isPalindrome(x) ? "Yes" : "No") << std::endl;
    std::cout << "y is palindrome: " << (isPalindrome(y) ? "Yes" : "No") << std::endl;
    return 0;
}

Output

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

x is palindrome: Yes
y is palindrome: No
deque.htm
Advertisements