C++ Map 库 - operator[] 函数
描述
C++ 函数 std::map::operator[] 如果键 k 匹配容器中的元素,则方法返回对该元素的引用。
声明
以下是 std::map::operator[] 函数形式 std::map 头的声明。
C++98
mapped_type& operator[] (const key_type& k);
C++11
mapped_type& operator[] (const key_type& k);
参数
k − 访问其映射值的元素的键。
返回值
返回对与键 k 关联的元素的引用。
异常
该成员不会抛出异常。
时间复杂度
Logarithmic i.e. O(lon n)
示例
以下示例显示了 std::map::operator[] 函数的用法。
#include <iostream>
#include <map>
using namespace std;
int main(void) {
/* Initializer_list constructor */
map<char, int> m = {
{'a', 1},
{'b', 2},
{'c', 3},
{'d', 4},
{'e', 5},
};
cout << "Map contains following elements" << endl;
cout << "m['a'] = " << m['a'] << endl;
cout << "m['b'] = " << m['b'] << endl;
cout << "m['c'] = " << m['c'] << endl;
cout << "m['d'] = " << m['d'] << endl;
cout << "m['e'] = " << m['e'] << endl;
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 −
Map contains following elements m['a'] = 1 m['b'] = 2 m['c'] = 3 m['d'] = 4 m['e'] = 5

