C++ unordered_multimap::emplace_hint() 函式



C++ 的unordered_multimap::emplace_hint()函式用於使用提示或位置在unordered_multimap中插入新元素。該位置僅作為提示;它不決定插入的位置,並且透過插入新元素將容器大小增加一。此函式類似於emplace()函式。

語法

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

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

引數

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

返回值

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

示例 1

在下面的示例中,讓我們看看emplace_hint()函式的使用。

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

輸出

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

Unordered multimap contains following elements
e = 3
b = 2
b = 2
c = 3
d = 4

示例 2

考慮下面的示例,我們將在此示例中在容器的起始位置和結束位置新增鍵值對。

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

輸出

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

multimap contains following elements before
Akash = 500
Vivek = 485
Sonam = 450
Aman = 490
after use of the emplace_hint() function 
multimap contains following elements
Aman = 460
Aman = 490
Sonam = 450
Vivek = 440
Vivek = 485
Akash = 460
Akash = 500

示例 3

讓我們看下面的例子,我們將使用emplace_hint()並將鍵值對儲存在隨機順序中。

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

輸出

上述程式碼的輸出如下:

The unordered_multimap contains following element : 
KEY	ELEMENT
3	March
3	April
2	May
2	February
1	Jun
1	January
廣告