C++ multimap::emplace() 函数



C++ 的 std::multimap::emplace() 函数用于将新的键值对插入容器中。与 insert() 函数不同,insert() 函数复制或移动元素,而 emplace() 函数通过消除不必要的复制来就地构造元素。它直接将参数转发到元素的构造函数。由于 multimap 允许具有相同键的多个元素,因此 emplace() 在插入元素时特别有用,无需创建和管理临时对。

语法

以下是 std::multimap::emplace() 函数的语法。

iterator 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.

返回值

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

示例

让我们看下面的例子,我们将演示 emplace() 函数的使用。

Open Compiler
#include <iostream> #include <map> int main() { std::multimap<int, std::string> a; a.emplace(1, "TP"); a.emplace(2, "TutorialsPoint"); for (const auto& x : a) { std::cout << x.first << ": " << x.second << std::endl; } return 0; }

输出

以上代码的输出如下:

1: TP
2: TutorialsPoint

示例

考虑另一种情况,我们将使用不同的键插入多个元素。

Open Compiler
#include <iostream> #include <map> int main() { std::multimap<int, std::string> a; a.emplace(1, "Hi"); a.emplace(2, "Namaste"); a.emplace(1, "Hello"); for (const auto& x : a) { std::cout << x.first << ": " << x.second << std::endl; } return 0; }

输出

如果我们运行以上代码,它将生成以下输出:

1: Hi
1: Hello
2: Namaste

示例

在下面的示例中,我们将使用移动语义将新元素插入到 multimap 中。

Open Compiler
#include <iostream> #include <map> #include <utility> int main() { std::multimap<int, std::string> a; a.emplace(std::make_pair(1, "Hi")); a.emplace(2, std::move(std::string("Hello"))); for(const auto& pair : a) { std::cout << pair.first << ": " << pair.second << std::endl; } return 0; }

输出

以下是以上代码的输出:

1: Hi
2: Hello
multimap.htm
广告