C ++映射 at() strong>函数用于通过给定的键值 strong>访问映射中的元素。如果所访问的密钥不存在于地图中,则会抛出异常 __ range strong>。
考虑键值 k strong>,语法为:
mapped_type& at (const key_type& k); const mapped_type& at (const key_type& k) const;
k strong>:要访问其映射值的元素的键值。
它使用键值返回对元素映射值的引用。
让我们看一个访问元素的简单示例。
#include <iostream> #include <string> #include <map> using namespace std; int main () { map<string,int> m = { { "A", 10 }, { "B", 20 }, { "C", 30 } }; for (auto& x: m) { cout << x.first << ": " << x.second << '\n'; } return 0; }
输出 strong>:
A: 10 B: 20 C: 30
在上面,at()函数用于访问map的元素。
让我们看一个简单的示例,使用它们的键值添加元素。
#include <iostream> #include <string> #include <map> using namespace std; int main () { map<int,string> mymap = { { 101, "" }, { 102, "" }, { 103, ""} }; mymap.at(101) = "Java"; mymap.at(102) = "T"; mymap.at(103) = "Point"; // prints value associated with key 101, i.e. Java cout<<mymap.at(101); // prints value associated with key 102, i.e T cout<<mymap.at(102); // prints value associated with key 103, i.e Point cout<<mymap.at(103); return 0; }
输出 strong>:
JavaTPoint
在上面的示例中,使用at()函数在初始化后使用关联的键值添加元素。
让我们看一个简单的示例,以更改与键值关联的值。
#include <iostream> #include <string> #include <map> using namespace std; int main () { map<int,string> mymap = { { 100, "Nikita"}, { 200, "Deep" }, { 300, "Priya" }, { 400, "Suman" }, { 500, "Aman" }}; cout<<"Elements are:" <<endl; for (auto& x: mymap) { cout << x.first << ": " << x.second << '\n'; } mymap.at(100) = "Nidhi"; // changes the value associated with key 100 to Nidhi mymap.at(300) = "Pinku"; // changes the value associated with key 300 to Pinku mymap.at(500) = "Arohi"; // changes the value associated with key 500 to Arohi cout<<"\nElements after make changes are:" <<endl; for (auto& x: mymap) { cout << x.first << ": " << x.second << '\n'; } return 0; }
输出 strong>:
Elements are: 100: Nikita 200: Deep 300: Priya 400: Suman 500: Aman Elements after make changes are: 100: Nidhi 200: Deep 300: Pinku 400: Suman 500: Arohi
在上面的示例中,at()函数用于更改与其键值关联的值。
让我们看一个简单的示例来处理"超出范围"?例外。
#include <iostream> #include <string> #include <map> using namespace std; int main () { map<char,string> mp = { { 'a',"Java"}, { 'b', "C++" }, { 'c', "Python" }}; cout<<endl<<mp.at('a'); cout<<endl<<mp.at('b'); cout<<endl<<mp.at('c'); try { mp.at('z'); // since there is no key with value z in the map, it throws an exception } catch(const out_of_range &e) { cout<<endl<<"Out of Range Exception at "<<e.what(); }
输出 strong>:
Java C++ Python Out of Range Exception at map::at
上面的示例抛出out_of_range异常,因为在映射中没有值为z的键。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)
PPT设计进阶 · 从基础操作到高级创意 -〔李金宝(Bobbie)〕