C++ multimap::rend() Function



The C++ std::multimap::rend() function is used to return a reverse iterator pointing to the element preceding the first element of the multimap. It is used in reverse traversal of the multimap, starting from the last element to the first. The rend() iterator is a position before the beginning, enabling safe reverse iteration. This function does not modify the multimap, it only provides a means to navigate through it in reverse order. The time complexity of this function is constant i.e. O(1).

Syntax

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

reverse_iterator rend() nothrow;
const_reverse_iterator rend() const nothrow;

Parameters

It does not accept any parameters.

Return value

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

Example

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

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

Output

Following is the output of the above code −

3: Hi
2: Hello
1: Vanakam

Example

Consider the following example, where we are going to check if the multimap is empty by comparing rend() with rbegin().

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a;
    if (a.rend() == a.rbegin()) {
        std::cout << "Multimap Is Empty." << std::endl;
    } else {
        std::cout << "Multimap Is Not Empty." << std::endl;
    }
    return 0;
}

Output

Output of the above code is as follows −

Multimap Is Empty.

Example

In the following example, we are going to find the elements with key and iterate over the multimap in reverse order, strating from the end of the found range.

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a = {{3, "BMW"}, {1, "Cruze"}, {2, "City"}, {1, "Sail"}};
    auto b = a.equal_range(2);
    for (auto x = std::make_reverse_iterator(b.second); x != a.rend(); ++x) {
        std::cout << x->first << " --> " << x->second << std::endl;
    }
    return 0;
}

Output

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

2 --> City
1 --> Sail
1 --> Cruze
multimap.htm
Advertisements