在本文中,我们将讨论C ++ STL中映射等于'[]'运算符的工作,语法和示例。
映射是关联容器,它有助于按特定顺序存储由键值和映射值的组合形成的元素。在映射容器中,数据始终在内部借助其关联的键进行排序。映射容器中的值通过其唯一键访问。
map::operator []是引用运算符。该运算符用于通过键访问容器中的元素。
如果容器中没有匹配的键,则运算符将使用该键插入一个新元素,并返回映射值的引用。该运算符的工作原理与map::at()相同,唯一的区别是,at()当映射容器中没有键时,抛出异常。
Map_name[key& k];
容器中只有1参数,即我们要引用的键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