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 − 它指定转发到构造新元素的参数。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

返回值

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

示例 1

在下面的示例中,让我们看看emplace_hint()函数的使用。

Open Compiler
#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

考虑下面的示例,我们将在此示例中在容器的起始位置和结束位置添加键值对。

Open Compiler
#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()并将键值对存储在随机顺序中。

Open Compiler
#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
广告