C++ unordered_map::emplace() 函数



C++ 函数unordered_map::emplace()用于向容器插入新元素,并使容器大小增加一。只有当键不存在于容器中时,插入才会发生,这使得键是唯一的。

如果多次放置相同的键,地图只存储第一个元素,因为地图是一个不存储多个相同键值的容器。

语法

以下是 unordered_map::emplace() 函数的语法:

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

参数

  • args − 表示要转发到元素构造函数的参数。

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

返回值

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

示例 1

让我们看看 unordered_map::emplace() 函数的基本用法。

Open Compiler
#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() 函数添加另外两个键值对。

Open Compiler
#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() 函数更改现有键的值,如下所示:

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