C++ 映射库 - emplace() 函数



描述

C++ 函数std::map::emplace() 通过插入新元素来扩展容器。

只有当键不存在时才会进行插入。

声明

以下是来自 `std::map` 头文件的 `std::map::emplace()` 函数的声明。

C++11

template <class... Args>
pair<iterator,bool> emplace (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.

参数

args − 传递给元素构造函数的参数。

返回值

返回一对:bool指示是否发生了插入,以及指向新插入元素的迭代器。

异常

如果任何操作抛出异常,则此函数无效。

时间复杂度

对数,即 log(n)

示例

以下示例演示了 `std::map::emplace()` 函数的使用。

#include <iostream>
#include <map>

using namespace std;

int main(void) {
   /* Initializer_list constructor */
   map<char, int> m;

   m.emplace('a', 1);
   m.emplace('b', 2);
   m.emplace('c', 3);
   m.emplace('d', 4);
   m.emplace('e', 5);

   cout << "Map contains following elements in reverse order" << endl;

   for (auto it = m.begin(); it != m.end(); ++it)
      cout << it->first << " = " << it->second << endl;

   return 0;
}

让我们编译并运行上述程序,这将产生以下结果:

Map contains following elements in reverse order
a = 1
b = 2
c = 3
d = 4
e = 5
map.htm
广告