C ++ map at()函數(shù)用于通過給定的鍵值訪問map中的元素。如果map中不存在所訪問的鍵,則拋出out_of _range異常。
假設(shè)鍵值為k,語法為:
mapped_type& at (const key_type& k); const mapped_type& at (const key_type& k) const;
k:要訪問其map值的元素的鍵值。
它使用鍵值返回對(duì)元素map值的引用。
讓我們看一個(gè)訪問元素的簡(jiǎn)單示例。
#include <iostream>
#include <string>
#include <map>
int main ()
{
map<string,int> m = {
{ "A", 10 },
{ "B", 20 },
{ "C", 30 } };
for (auto& x: m) {
cout << x.first << ": " << x.second << '\n';
}
return 0;
}輸出:
A: 10 B: 20 C: 30
在上面,at()函數(shù)用于訪問map的元素。
讓我們看一個(gè)簡(jiǎn)單的示例,使用它們的鍵值添加元素。
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main ()
{
map<int,string> mymap= {
{ 101, "" },
{ 102, "" },
{ 103, ""} };
mymap.at(101) = "nhooo";
mymap.at(102) = ".";
mymap.at(103) = "com";
//打印鍵101的值,即nhooo
cout<<mymap.at(101);
// 打印鍵102的值,即.
cout<<mymap.at(102);
// 打印鍵103的值,即 com
cout<<mymap.at(103);
return 0;
}輸出:
(cainiaoplus.com)
在上面的示例中,使用at()函數(shù)在初始化后使用關(guān)聯(lián)的鍵值添加元素。
讓我們看一個(gè)簡(jiǎn)單的示例,以更改與鍵值關(guān)聯(lián)的值。
#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<<"元素是:" <<endl;
for (auto& x: mymap) {
cout << x.first << ": " << x.second << '\n';
}
mymap.at(100) = "Nidhi"; // 將鍵100的值更改為Nidhi
mymap.at(300) = "Pinku"; // 將鍵300的值更改為 Pinku
mymap.at(500) = "Arohi"; // 將鍵500的值更改為 Arohi
cout<<"\n更改后元素是:" <<endl;
for (auto& x: mymap) {
cout << x.first << ": " << x.second << '\n';
}
return 0;
}輸出:
元素是: 100: Nikita 200: Deep 300: Priya 400: Suman 500: Aman 更改后元素是: 100: Nidhi 200: Deep 300: Pinku 400: Suman 500: Arohi
在上面的示例中,at()函數(shù)用于更改與其鍵值關(guān)聯(lián)的值。
讓我們看一個(gè)簡(jiǎn)單的示例來處理“超出范圍”?例外。
#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');
// 因?yàn)閙ap中沒有值為z的鍵,所以它會(huì)拋出一個(gè)異常
} catch(const out_of_range &e) {
cout<<endl<<"Out of Range Exception at "<<e.what();
}輸出:
Java C++ Python Out of Range Exception at map::at
上面的示例拋出out_of_range異常,因?yàn)樵趍ap中沒有值為z的鍵。