map::operator[]
描述 (Description)
C ++函数std::map::operator[]如果键k匹配容器中的元素,则method返回对元素的引用。
声明 (Declaration)
以下是std :: map :: operator []函数形式std :: map头的声明。
C++98
mapped_type& operator[] (const key_type& k);
C++11
mapped_type& operator[] (const key_type& k);
参数 (Parameters)
k - 访问其映射值的元素的键。
返回值
返回对与键k关联的元素的引用。
异常 (Exceptions)
该成员不会抛出异常。
时间复杂
对数即O(lon n)
例子 (Example)
以下示例显示了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