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



描述

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

宣告

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

C++11

mapped_type& operator[](const 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'] = " << um['a'] << endl;
   cout << "um['b'] = " << um['b'] << endl;
   cout << "um['c'] = " << um['c'] << endl;
   cout << "um['d'] = " << um['d'] << endl;
   cout << "um['e'] = " << 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
廣告