C++ multimap::emplace() Function



The C++ std::multimap::emplace() function is used to insert a new key-value pair into the container. Unlike insert() function, which copies or moves the element, emplace() constructs the element in place by eliminating unnecessary copies. It directly forwards the arguments to the constructor of the element. Since multimap allows multiple elements with the same key, emplace() is particularly useful for inserting elements without needing to create and manage temporary pairs.

Syntax

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

iterator emplace (Args&&... args);

Parameters

  • args − arguments to forward to the constructor of the element.

Return value

This function returns an iterator to newly inserted element.

Example

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

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a;
    a.emplace(1, "TP");
    a.emplace(2, "TutorialsPoint");
    for (const auto& x : a) {
        std::cout << x.first << ": " << x.second << std::endl;
    }
    return 0;
}

Output

Output of the above code is as follows −

1: TP
2: TutorialsPoint

Example

Consider the another scenario, where we are going to emplace multiple elements with different keys.

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

Output

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

1: Hi
1: Hello
2: Namaste

Example

In the following example, we are going to use the move semantics while inserting a new element into the multimap.

#include <iostream>
#include <map>
#include <utility>
int main()
{
    std::multimap<int, std::string> a;
    a.emplace(std::make_pair(1, "Hi"));
    a.emplace(2, std::move(std::string("Hello")));
    for(const auto& pair : a) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }
    return 0;
}

Output

Following is the output of the above code −

1: Hi
2: Hello
multimap.htm
Advertisements