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



描述

C++ 函数std::map::insert() 通过从初始化列表插入新元素来扩展映射。此函数将容器大小增加一。

声明

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

C++11

void insert (initializer_list<value_type> il);

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

参数

il − 初始化列表。

返回值

无。

异常

此成员函数不会抛出异常。

时间复杂度

对数,即 O(log n)。

示例

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

#include <iostream>
#include <map>

using namespace std;

int main(void) {
   map<char, int> m = {
            {'b', 2},
            {'c', 3},
            {'d', 4},
            };

   m.insert({{'e', 5}, {'a', 1}});

   cout << "Map contains following elements" << endl;

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

   return 0;
}

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

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