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



描述

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

宣告

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

C++98

pair<iterator,bool> insert (const value_type& val);

C++11

pair<iterator,bool> insert (const value_type& val);

引數

val - 要插入的值。

返回值

返回一對:bool指示是否發生了插入,並返回指向新插入元素的迭代器。

異常

此成員函式不丟擲異常。

時間複雜度

對數,即 O(log n)

示例

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

#include <iostream>
#include <map>

using namespace std;

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

   m.insert(pair<char, int>('d', 4));
   m.insert(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
廣告