C++ STL 中的 map::at()


在本文中,我們將討論 C++ STL 中 map::at() 函式的工作原理、語法和示例。

什麼是 C++ STL 中的 Map?

Map 是關聯容器,它便於以特定順序儲存由鍵值和對映值組合而成的元素。在 map 容器中,資料在內部始終透過其關聯的鍵進行排序。透過其唯一鍵訪問 map 容器中的值。

什麼是 map::at()?

map::at() 函式是 C++ STL 中的內建函式,它定義在 header file. at() is used to access a specific element of the associated map container. This function returns a reference to the specific value which is associated with the key.

當鍵與 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

更新於:15-Apr-2020

337 次觀看

開啟 職業生涯

完成課程獲得認證

開始學習
廣告