C++ multimap::emplace_hint() Function



The C++ std::multimap::emplace_hint() function allows the insertion of elements with a specified position hint, avoiding the unnecessary lookups. It constructs the element in place at the hinted position if it does not exist, based on the provided arguments. This method is useful for maintaining the sorted order and minimizing the number of comparisons during insertions.

Syntax

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

iterator emplace_hint (const_iterator position, Args&&... args);

Parameters

  • position − It indicates the hint for the position to insert element.
  • args − It is the arguments forwarded to construct the new element.

Return value

This function returns an iterator to the newly inserted element.

Exceptions

It does not make any changes on container if exception is thrown.

Time complexity

The time complexity of this function is Logarithmic i.e. O(log n)

Example

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

#include 
#include 
int main()
{
    std::multimap a;
    auto x = a.emplace_hint(a.end(), 1, "Hi");
    a.emplace_hint(x, 2, "Hello");
    a.emplace_hint(a.end(), 1, "Namaste");
    for (const auto& pair : a) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }
    return 0;
}

Output

Output of the above code is as follows −

1: Hi
1: Namaste
2: Hello

Example

Consider the following example, where we are going to use the emplace_hint() function for range insertion.

#include 
#include 
int main()
{
    std::multimap a = {{1, "Audi"}, {2, "BMW"}};
    std::multimap b = {{1, "Ciaz"}, {3, "Ducati"}};
    auto x = a.begin();
    for (const auto& pair : b) {
        x = a.emplace_hint(x, pair.first, pair.second);
    }
    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: Ciaz
1: Audi
2: BMW
3: Ducati

Example

In the following example, we are going to use emplace_hint() with move semantics.

#include 
#include 
#include 
int main()
{
    std::multimap a = {{1, "TP"}, {2, "TutorialsPoint"}};
    auto x = a.end();
    std::string y = "Tutorix";
    x = a.emplace_hint(x, 3, std::move(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 −

1: TP
2: TutorialsPoint
3: Tutorix
multimap.htm
Advertisements