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



描述

C++ 函式std::unordered_map::unordered_map() 使用初始化列表構造一個無序對映。

宣告

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

C++11

unordered_map(initializer_list<value_type> il,
              size_type n = /* Implementation defined */,
              const hasher& hf = hasher(),
              const key_equal& eql = key_equal(),
              const allocator_type& alloc = allocator_type()
              );

引數

  • il - 初始化列表物件。

  • n - 最大初始桶數。

  • hf - 要使用的雜湊函式。

  • eql - 比較函式物件,如果提供的兩個容器物件被認為相等則返回 true。

  • alloc - 用於此容器所有記憶體分配的分配器。

返回值

建構函式不返回值。

時間複雜度

平均情況下為線性,即 O(n)。

最壞情況下為平方,即 O(n2)。

示例

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

#include <iostream>
#include <unordered_map>

using namespace std;

int main(void) {
   unordered_map<char, int> um {
            {'a', 1},
            {'b', 2},
            {'c', 3},
            {'d', 4},
            {'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
b = 2
c = 3
d = 4
unordered_map.htm
廣告