C++ 無序對映庫 - unordered_map() 函式



描述

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

宣告

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

C++11

template <class P>
iterator insert (const_iterator position, P&& val);

引數

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

  • val − 要插入的值。

返回值

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

時間複雜度

平均情況為常數,即 O(1)。

最壞情況為線性,即 O(n)。

示例

以下示例顯示了 std::unordered_map::insert() 函式的用法。

#include <iostream>
#include <unordered_map>

using namespace std;

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

   um.insert(move(um.begin()), pair<char, int>('a', 1));
   um.insert(move(um.end()), pair<char, int>('e', 5));

   cout << "Unordered map contains following elements" << endl;

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

   return 0;
}

讓我們編譯並執行上述程式,這將產生以下結果:

Unordered map contains following elements
e = 5
a = 1
d = 4
b = 2
c = 3
unordered_map.htm
廣告