unordered_map::operator[]
描述 (Description)
C ++函数std::unordered_map::operator[]如果键k匹配容器中的元素,则method返回对该元素的引用。
声明 (Declaration)
以下是std :: unordered_map :: operator []函数形式std :: unordered_map头的声明。
C++11
mapped_type& operator[](const key_type& k);
参数 (Parameters)
k - 访问其映射值的元素的键。
返回值
返回对与键k关联的元素的引用。
时间复杂
常数,即平均情况下为O(1)。
在最坏的情况下线性即O(n)。
例子 (Example)
以下示例显示了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