C++ multimap::emplace_hint() 函式



C++ 的std::multimap::emplace_hint()函式允許插入具有指定位置提示的元素,避免不必要的查詢。如果基於提供的引數,目標位置不存在,它會在提示的位置就地構造元素。此方法有助於維護排序順序並最大限度地減少插入期間的比較次數。

語法

以下是 std::multimap::emplace_hint() 函式的語法。

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

引數

  • position − 指示插入元素的位置提示。
  • args − 用於構造新元素的轉發引數。

返回值

此函式返回指向新插入元素的迭代器。

異常

如果丟擲異常,它不會對容器進行任何更改。

時間複雜度

此函式的時間複雜度是對數的,即 O(log n)

示例

讓我們來看下面的例子,我們將演示 emplace_hint() 函式的基本用法。

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> 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;
}

輸出

以上程式碼的輸出如下:

1: Hi
1: Namaste
2: Hello

示例

考慮下面的例子,我們將使用 emplace_hint() 函式進行範圍插入。

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a = {{1, "Audi"}, {2, "BMW"}};
    std::multimap<int, std::string> 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;
}

輸出

以下是以上程式碼的輸出:

1: Ciaz
1: Audi
2: BMW
3: Ducati

示例

在下面的例子中,我們將使用帶有移動語義的 emplace_hint()。

#include <iostream>
#include <map>
#include <utility>
int main()
{
    std::multimap<int, std::string> 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;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出:

1: TP
2: TutorialsPoint
3: Tutorix
multimap.htm
廣告