C++ 無序對映庫 - operator[] 函式



描述

C++ 函式 std::unordered_map::operator[] 如果鍵k匹配容器中的元素,則該方法返回對該元素的引用。

宣告

以下是來自 std::unordered_map 標頭檔案的 std::unordered_map::operator[] 函式的宣告。

C++11

mapped_type& operator[](key_type&& k);

引數

k − 訪問其對映值的元素的鍵。

返回值

返回與鍵關聯的元素的引用k.

時間複雜度

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

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

示例

以下示例顯示了 std::unordered_map::operator[] 函式的使用。

#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;

   cout << "um['a'] = " << move(um['a']) << endl;
   cout << "um['b'] = " << move(um['b']) << endl;
   cout << "um['c'] = " << move(um['c']) << endl;
   cout << "um['d'] = " << move(um['d']) << endl;
   cout << "um['e'] = " << move(um['e']) << endl;

   return 0;
}

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

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