地图 是以映射方式存储元素的关联容器。每个元素都有一个键值和一个映射值。没有两个映射值可以具有相同的键值。
null
map::operator[]
该运算符用于参考运算符内部给定位置处的元素。它与at()函数类似,唯一的区别是,当位置不在贴图大小的范围内时,at()函数抛出超出范围的异常,而此运算符会导致未定义的行为。 语法:
mapname[key]Parameters :Key value mapped to the element to be fetched.Returns :Direct reference to the element at the given key value.
例如:
Input : map mymap; mymap['a'] = 1; mymap['a'];Output : 1Input : map mymap; mymap["abcd"] = 7; mymap["abcd"];Output : 7
错误和异常 1.如果密钥不在地图中,则显示未定义的行为。 2.除此之外,它也不例外。
CPP
// CPP program to illustrate // Implementation of [] operator #include <map> #include <iostream> #include<string> using namespace std; int main() { // map declaration map< int ,string> mymap; // mapping integers to strings mymap[1] = "Hi" ; mymap[2] = "This" ; mymap[3] = "is" ; mymap[4] = "GeeksForGeeks" ; // using operator[] to print string // mapped to integer 4 cout << mymap[4]; return 0; } |
输出:
GeeksForGeeks
时间复杂性: O(logn)
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END