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.