C++ multimap::crend() Function



The C++ std::multimap::crend() function is used to return a constant reverse iterator to the element preceding the first element of the multimap, marking its end in reverse order. This itearor cannot be used to modify the elements it points to. It is used to iterator over the multimap in reverse without altering the elements, ensuring read-only access. The time complexity of this function is constant i.e.O(1).

Syntax

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

const_reverse_iterator crend() const noexcept;

Parameters

It does not accepts any parameter

Return value

This function returns a constant reverse iterator.

Example

In the following example, we are going to demonstrate the usage of crend() function.

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a = {{2, "B"}, {1, "C"}, {3, "A"}};
    for (auto x = a.crbegin(); x != a.crend(); ++x) {
        std::cout << x->first << ": " << x->second << std::endl;
    }
    return 0;
}

Output

Following is the output of the above code −

3: A
2: B
1: C

Example

Consider the following example, where we are going to check whether the multimap is empty or not.

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a;
    if (a.crbegin() == a.crend()) {
        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 largest key in the multimap.

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a = {{4, "A"}, {3, "B"}, {1, "C"}};
    auto x = a.crbegin();
    if (x != a.crend()) {
        std::cout << "" << x->first << std::endl;
    }
    return 0;
}

Output

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

4

Example

Following is the example, where we are going to count the number of elements in the multimap with the value "B".

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a = {{3, "A"}, {1, "B"}, {1, "B"}, {1, "B"}};
    int x = 0;
    for (auto y = a.crbegin(); y != a.crend(); ++y) {
        if (y->second == "B") {
            ++x;
        }
    }
    std::cout << " " << x << std::endl;
    return 0;
}

Output

Let us compile and run the above program, this will produce the following result −

3
multimap.htm
Advertisements