C++ 對映庫 - insert() 函式



描述

C++ 函式std::map::insert()透過在對映中插入新元素來擴充套件容器。此函式使容器大小增加一。

宣告

以下是來自 std::map 標頭檔案的 std::map::insert() 函式的宣告。

C++98

iterator insert (iterator position, const value_type& val);

C++11

iterator insert (const_iterator position, const value_type& val);

引數

  • position - 插入元素的位置提示。

  • val - 要插入的值。

返回值

返回一個指向新插入元素的迭代器。

異常

此成員函式不丟擲異常。

時間複雜度

對數,即 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(m.begin(), pair<char, int>('a', 1));
   m.insert(m.end(), pair<char, int>('e', 5));

   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
廣告