C++ STL 中的 map::at()
在本文中,我们将讨论 C++ STL 中 map::at() 函数的工作原理、语法和示例。
什么是 C++ STL 中的 Map?
Map 是关联容器,它便于以特定顺序存储由键值和映射值组合而成的元素。在 map 容器中,数据在内部始终通过其关联的键进行排序。通过其唯一键访问 map 容器中的值。
什么是 map::at()?
map::at() 函数是 C++ STL 中的内置函数,它定义在
当键与 map 容器的任何键不匹配时,该函数会引发 out_of_range 异常。
语法
map_name.at(key& k);
参数
该函数接受一个参数,即
返回值
此函数返回对与我们正在寻找的键 k 关联的值的引用。
示例
输入
std::map<int> mymap;
mymap.insert({‘a’, 10});
mymap.insert({‘b, 20});
mymap.insert({‘c, 30});
mymap.at(‘b’);输出
b: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;
TP_2[5] = 50;
TP_2[6] = 60;
TP_2[7] = 70;
cout<<"Elements at TP_1[1] = "<< TP_1.at(1) << endl;
cout<<"Elements at TP_1[2] = "<< TP_1.at(2) << endl;
cout<<"Elements at TP_1[3] = "<< TP_1.at(3) << endl;
cout<<"\nElements at TP_2[7] = "<< TP_2.at(7) << endl;
cout<<"Elements at TP_2[5] = "<< TP_2.at(5) << endl;
return 0;
}输出
Elements at TP_1[1] = 10 Elements at TP_1[2] = 20 Elements at TP_1[3] = 30 Elements at TP_1[7] = 70 Elements at TP_1[5] = 50
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP