C++ unordered_map::emplace() 函式



C++ 函式unordered_map::emplace()用於向容器插入新元素,並使容器大小增加一。只有當鍵不存在於容器中時,插入才會發生,這使得鍵是唯一的。

如果多次放置相同的鍵,地圖只儲存第一個元素,因為地圖是一個不儲存多個相同鍵值的容器。

語法

以下是 unordered_map::emplace() 函式的語法:

pair<iterator, bool>  emplace( Args&&... args);

引數

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

返回值

返回一個pair,包含一個bool值(指示是否發生了插入)和一個指向新插入元素的迭代器。

示例 1

讓我們看看 unordered_map::emplace() 函式的基本用法。

#include <iostream>
#include <unordered_map>
using namespace std;
int main(void) {
   unordered_map<char, int> um;
   um.emplace('a', 1);
   um.emplace('b', 2);
   um.emplace('c', 3);
   um.emplace('d', 4);
   um.emplace('e', 5);
   cout << "Unordered map contains following elements" << endl;
   for (auto it = um.begin(); it != um.end(); ++it)
      cout << it->first << " = " << it->second << endl;
   return 0;
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Unordered map contains following elements
e = 5
d = 4
c = 3
b = 2
a = 1

示例 2

在下面的示例中,我們建立了一個 unordered_map,然後我們將使用 emplace() 函式新增另外兩個鍵值對。

#include <iostream>
#include <unordered_map>
using namespace std;
int main(void) {
   unordered_map<string, int> um = {{"Aman", 490},{"Vivek", 485},{"Akash", 500},{"Sonam", 450}};
   cout << "Unordered map contains following elements before" << endl;
   for (auto it = um.begin(); it != um.end(); ++it)
      cout << it->first << " = " << it->second << endl;
   cout<<"after use of the emplace function \n";
   um.emplace("Sarika", 440);
   um.emplace("Satya", 460);
   cout << "Unordered map contains following elements" << endl;
   for (auto it = um.begin(); it != um.end(); ++it)
      cout << it->first << " = " << it->second << endl;
   return 0;
}

輸出

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

Unordered map contains following elements before
Sonam = 450
Akash = 500
Vivek = 485
Aman = 490
after use of the emplace function 
Unordered map contains following elements
Sarika = 440
Satya = 460
Sonam = 450
Akash = 500
Vivek = 485
Aman = 490

示例 3

考慮下面的示例,我們嘗試使用 emplace() 函式更改現有鍵的值,如下所示:

#include <iostream>
#include <unordered_map>
using namespace std;
int main(void) {
   unordered_map<string, int> um = {{"Aman", 490},{"Vivek", 485},{"Akash", 500},{"Sonam", 450}};
   cout << "Unordered map contains following elements before usages of emplace" << endl;
   for (auto it = um.begin(); it != um.end(); ++it)
      cout << it->first << " = " << it->second << endl;
   um.emplace("Aman", 440);
   um.emplace("Sonam", 460);
   cout << "Unordered map contains same elements after the usages of emplace() function" << endl;
   for (auto it = um.begin(); it != um.end(); ++it)
      cout << it->first << " = " << it->second << endl;
   return 0;
}

輸出

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

Unordered map contains following elements before
Sonam = 450
Akash = 500
Vivek = 485
Aman = 490
Unordered map contains same elements after the usages of emplace() function
Sonam = 450
Akash = 500
Vivek = 485
Aman = 490
廣告