當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ Unordered_map unordered_map()用法及代碼示例


描述

C++ 函數std::unordered_map::unordered_map()構造一個 unordered_map 的元素數量與範圍內的一樣多第一的最後的

聲明

以下是 std::unordered_map::unordered_map() 函數形式 std::unordered_map 頭文件的聲明。

C++11

unordered_map(InputIterator first, InputIterator last,
              size_type n = /* Implementation defined */,
              const hasher& hf = hasher(),
              const key_equal& eql = key_equal(),
              const allocator_type& alloc = allocator_type()
             );

參數

  • first− 將迭代器輸入到初始位置。

  • last− 將迭代器輸入到最終位置。

  • 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> um1 = {
            {'a', 1},
            {'b', 2},
            {'c', 3},
            {'d', 4},
            {'e', 5}
            };

   unordered_map<char, int>um2(um1.begin(), um2.end());

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

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

   return 0;
}

讓我們編譯並運行上麵的程序,這將產生以下結果 -

Unordered_map contains following elements
a = 1
b = 2
c = 3
d = 4
e = 5

相關用法


注:本文由純淨天空篩選整理自 C++ Unordered_map Library - unordered_map() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。