C++ multimap::rbegin() Function



The C++ std::multimap::rbegin() function is used to return a reverse iterator pointing to the last element, enabling reverse traversal from the last element to the first element. This function is useful for operations that require accessing elements in reverse order. The reverse iterator can be incremented to move backward through the container. The time complexity of this function is constant i.e. O(1).

Syntax

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

reverse_iterator rbegin() nothrow;
const_reverse_iterator rbegin() const nothrow;

Parameters

It does not accepts any parameter.

Return value

This function return a reverse iterator to the beginning of the container.

Example

Let's look at the following example, where we are going to demonstrate the usage of rbegin() function.

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a = {{1, "Hi"}, {1, "Hello"}, {2, "Vanakam"}};
    auto x = a.rbegin();
    std::cout << x->first << ": " << x->second << std::endl;
    return 0;
}

Output

Output of the above code is as follows −

2: Vanakam

Example

Consider the following example, where we are going to search and print for a specific value using a reverse iterator.

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a;
    a.insert({1, "AB"});
    a.insert({2, "BC"});
    auto x = a.rbegin();
    while (x != a.rend()) {
        if (x->second == "AB") {
            std::cout << "Founded Key Value Is : " << x->first << " " << x->second << std::endl;
            break;
        }
        ++x;
    }
    return 0;
}

Output

Following is the output of the above code −

Founded Key Value Is : 1 AB

Example

In the following example, we are going to count the number of elements in the multimap using a reverse iterator.

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a;
    a.insert({1, "TP"});
    a.insert({2, "Tutorix"});
    a.insert({3, "Tutorialspoint"});
    int count = 0;
    for (auto x = a.rbegin(); x != a.rend(); ++x) {
        count++;
    }
    std::cout << "Total Elements: " << count << std::endl;
    return 0;
}

Output

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

Total Elements: 3
multimap.htm
Advertisements