C++ unordered_map::emplace_hint() 函式



C++ 函式 unordered_map::emplace_hint() 使用提示或位置在 unordered_map 中插入一個新元素。該位置僅作為提示;它不決定插入操作要執行的位置,並且透過插入新元素將容器大小擴充套件一個。此函式類似於 emplace() 函式,並且僅當鍵不存在時才進行插入,表示鍵應該是唯一的。

如果多次放置相同的鍵,則對映僅儲存第一個元素,因為對映是不儲存多個相同值鍵的容器。

語法

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

unordered_map.emplace_hint(position, key, element);

引數

  • position - 插入元素的位置提示。容器可以使用此值來最佳化操作。

  • key - 它指定要插入到 unordered_multimap 中的鍵。

  • element - 它指定要插入到 unordered_multimap 中的元素/值。

返回值

返回指向新插入元素的迭代器。如果由於元素已存在而插入失敗,則返回指向現有元素的迭代器。

示例 1

考慮以下示例,我們將在其中演示 emplace_hint() 函式的用法。

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

輸出

以上程式碼的輸出如下:

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

示例 2

在以下示例中,我們將使用 emplace_hint() 函式並將鍵/值對新增到容器的起始位置。

#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_hint() function \n";
   um.emplace_hint(um.begin(), "Sarika", 440);
   um.emplace_hint(um.begin(), "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_hint() function 
Unordered map contains following elements
Sarika = 440
Satya = 460
Sonam = 450
Akash = 500
Vivek = 485
Aman = 490

示例 3

讓我們看一下以下示例,我們將在其中建立一個 unordered_map 並使用 emplace_hint() 函式以隨機順序儲存鍵值對。

#include <iostream>
#include <unordered_map>
using namespace std;
int main() { 
   unordered_map<int, string> Umap;
   Umap.emplace_hint(Umap.begin(), 1, "January");
   Umap.emplace_hint(Umap.begin(), 2, "February");
   Umap.emplace_hint(Umap.begin(), 3, "March");
 
   cout << "The unordered_map is : \n";
   cout << "KEY\tELEMENT"<<endl;
   for (auto itr = Umap.begin(); itr != Umap.end(); itr++)
      cout << itr->first << "\t"<< itr->second << endl;
   return 0;
}

輸出

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

The unordered_map is : 
KEY	ELEMENT
3	March
2	February
1	January
廣告