C++ STL 程式中的 map::operator[]


在本文中,我們將討論 C++ STL 中 map 等於 '[]' 運算子的工作原理、語法和示例。

什麼是 C++ STL 中的 Map?

Map 是關聯容器,它可以方便地儲存由鍵值和對映值組合而成的元素,並按照特定順序排列。在 map 容器中,資料在內部始終透過其關聯的鍵進行排序。map 容器中的值可以透過其唯一的鍵進行訪問。

什麼是 map 等於 '[]' 運算子?

map::operator[] 是一個引用運算子。此運算子用於透過其鍵訪問容器中的元素。

如果容器中沒有匹配的鍵,則該運算子將插入一個具有該鍵的新元素,並返回對映值的引用。此運算子的工作方式與 map::at() 相同,唯一的區別是,當 map 容器中不存在鍵時,at() 會丟擲異常。

語法

Map_name[key& k];

引數

只有一個引數,即我們想要在容器中引用的鍵 k。

返回值

此運算子返回與鍵 k 關聯的值。

輸入 -

map<char, int> newmap;
newmap.insert({1, 20});
newmap.insert({2, 30});
newmap[1];

輸出 

20

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int main(){
   map<int, int> TP_1;
   map<int, int> TP_2;
   TP_1[1] = 10;
   TP_1[2] = 20;
   TP_1[3] = 30;
   TP_1[4] = 40;
   cout<<"Element at TP[3] is : "<<TP_1[3];
   return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出:

Element at TP[3] is : 30

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int main(){
   map<int, int> TP_1;
   map<int, int> TP_2;
   TP_1[1] = 10;
   TP_1[2] = 20;
   TP_1[3] = 30;
   TP_1[4] = 40;
   cout<<"Element at TP[3] is : "<<TP_1[3];
   if(TP_1[5]==0){
      cout<<"\nElement at TP[5] doesn't exist";
   }
   else{
      cout<<"Element at TP[5] is : "<<TP_1[5];
   }
   return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出:

Element at TP[3] is : 30
Element at TP[5] doesn't exist

更新於: 2020-08-14

383 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.