C++ Unordered_map 库 - operator[] 函数
描述
C++ 函数 std::unordered_map::operator[] 如果键 k 匹配容器中的元素,则方法返回对该元素的引用。
声明
以下是 std::unordered_map::operator[] 函数形式 std::unordered_map 头的声明。
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

