C++ multimap::erase() Function



The C++ std::multimap::erase() function is used to remove the elements from a container. This function has 3 primary overloads: one that erases elements by keys, another by iterator, and the third by a range of iterators (you can find the syntaxes of all the variants below).

When used with a key, all the elements with that key are removed. With an iterator the element point to it is erased,and the iterator becomes invalid. For a range, all elements within the specified range are erased.

Syntax

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

iterator  erase (const_iterator position);
or
size_type erase (const key_type& k);
or
iterator  erase (const_iterator first, const_iterator last);

Parameters

  • position − It indicates the iterator pointing to a single element to be removed.
  • k − It indicates the key to be removed from the multimap.
  • first, last − It indicates the iterators specifying a range within the multimap.

Return value

This function returns the number of elements erased for key-based version.

Example

Let's look at the following example, where we are going to erase elements by key.

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a = {
        {1, "AB"},
        {1, "BC"},
        {2, "CD"},
        {3, "DE"}
    };
    a.erase(1);
    for (const auto& pair : a) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }
    return 0;
}

Output

Output of the above code is as follows −

2: CD
3: DE

Example

Consider the following example, where we are going to erase the element by iterator.

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a = {
        {1, "A"},
        {2, "B"},
        {3, "C"}
    };
    auto x = a.begin();
    a.erase(x);
    for (const auto& pair : a) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }
    return 0;
}

Output

Following is the output of the above code −

2: B
3: C

Example

In the following example, we are going to erase the element by using the range of the iterator.

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a = {
        {1, "Hi"},
        {2, "Hello"},
        {3, "Namaste"},
        {3, "Vanakam"}
    };
    auto x = a.begin();
    auto y = std::next(x, 2);
    a.erase(x, y);
    for (const auto& pair : a) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }
    return 0;
}

Output

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

3: Namaste
3: Vanakam
multimap.htm
Advertisements