映射是關聯容器,以映射方式存儲元素。每個元素都有一個鍵值和一個映射值。任何兩個映射值都不能具有相同的鍵值。
Map::運算符[]
此運算符用於引用運算符內部給定位置處的元素。與 at() 函數類似,唯一的區別是 at() 函數在位置不在Map大小的範圍內時拋出超出範圍的異常,而該運算符會導致未定義的行為。
用法:
mapname[key] 參數: Key value mapped to the element to be fetched. 返回: Direct reference to the element at the given key value.
例子:
Input : map mymap; mymap['a'] = 1; mymap['a']; Output: 1 Input : map mymap; mymap["abcd"] = 7; mymap["abcd"]; Output: 7
錯誤和異常
1. 如果Map中不存在 key ,則顯示未定義的行為。
2. 否則它沒有異常拋出保證。
// 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(登錄)
相關用法
注:本文由純淨天空篩選整理自AyushSaxena大神的英文原創作品 map::operator[] in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。