C++ multimap::emplace() 函式



C++ 的 std::multimap::emplace() 函式用於將新的鍵值對插入容器中。與 insert() 函式不同,insert() 函式複製或移動元素,而 emplace() 函式透過消除不必要的複製來就地構造元素。它直接將引數轉發到元素的建構函式。由於 multimap 允許具有相同鍵的多個元素,因此 emplace() 在插入元素時特別有用,無需建立和管理臨時對。

語法

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

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

引數

  • args − 轉發到元素建構函式的引數。

返回值

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

示例

讓我們看下面的例子,我們將演示 emplace() 函式的使用。

#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;
}

輸出

以上程式碼的輸出如下:

1: TP
2: TutorialsPoint

示例

考慮另一種情況,我們將使用不同的鍵插入多個元素。

#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;
}

輸出

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

1: Hi
1: Hello
2: Namaste

示例

在下面的示例中,我們將使用移動語義將新元素插入到 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;
}

輸出

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

1: Hi
2: Hello
multimap.htm
廣告