C++ multimap::end() Function



The C++ std::multimap::end() function is used to return an iterator pointing to the past the end element in the container. This element acts as a placeholder and is not valid for dereferencing. It is mainly used to indicate the end of the multimap during iteration, allowing functions to loop through all elements correctly. The returned iterator is used fro determining when iteration or element search should stop, ensuring the entire range of elements has been processed.

Syntax

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

iterator end() noexcept;
const_iterator end() const noexcept;

Parameters

It does not accept any parameter.

Return value

This function returns an iterator pointing to the past the end element.

Example

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

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

Output

Output of the above code is as follows −

3 => C
2 => B
1 => A

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.begin() == a.end()) {
        std::cout << "Multimap is empty." << std::endl;
    } else {
        std::cout << "Multimap is not empty." << std::endl;
    }
    return 0;
}

Output

Following is the output of the above code −

Multimap is empty.

Example

In the following example, we are going to erase the element with specific key, and using the end() function to iterate and print remaining elements.

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a = {{3, "Cruze"}, {2, "Beats"}, {1, "Sail"}};
    a.erase(1);
    for (auto x = a.begin(); x != a.end(); ++x) {
        std::cout << x->first << " => " << x->second << std::endl;
    }
    return 0;
}

Output

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

2 => Beats
3 => Cruze

Example

Following is the example, where we are going to use find() to locate the key, if the key is found it prints the element otherwise it checks against end() to confirm element is not present.

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a = {{1, "A"}, {2, "B"}, {3, "C"}};
    auto x = a.find(3);
    if (x != a.end()) {
        std::cout << "Element Found : " << x->first << " => " << x->second << std::endl;
    } else {
        std::cout << "Element Not Found :" << std::endl;
    }
    return 0;
}

Output

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

Element Not Found
multimap.htm
Advertisements