C++ unordered_map::at() 函式



C++ 的unordered_map::at()函式用於檢索給定專案鍵等效於key的對映值的引用,或者我們可以說它返回具有元素作為鍵“k”的值的引用。

如果專案不存在,則丟擲型別為“out of range”的異常。使用此函式,我們可以訪問對映值並修改它們。

語法

以下是 std::unordered_map::at() 函式的語法。

name_of_Unordered_map.at(k)

引數

k − 訪問其對映值的鍵值。

返回值

如果物件具有常量限定符,則方法返回對對映值的常量引用;否則返回對非常量值的引用。

示例 1

讓我們考慮以下示例,我們將演示 std::unordered_map::at() 函式的使用。

#include <iostream>
#include <unordered_map>
using namespace std;
int main(void) {
   unordered_map<char, int> um = {
      {'a', 1},
      {'b', 2},
      {'c', 3},
      {'d', 4},
      {'e', 5}
   };
   cout << "Value of key um['a'] = " << um.at('a') << endl;
   try {
      um.at('z');
   } catch(const out_of_range &e) {
      cerr << "Exception at " << e.what() << endl;
   }
   return 0;
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Value of key um['a'] = 1
Exception at _Map_base::at

示例 2

在下面的示例中,我們將返回對映中不存在的鍵,並觀察輸出。

#include <iostream>
#include <unordered_map>
using namespace std;
int main(void) {
   unordered_map<char, int> um = {
      {'a', 1},
      {'b', 2},
      {'c', 3},
      {'d', 4},
      {'e', 5}
   };
   cout << "Value of key um['z'] = " << um.at('z') << endl;
   return 0;
}

輸出

如果我們執行上述程式碼,它將生成以下輸出:

terminate called after throwing an instance of 'std::out_of_range'
  what():  _Map_base::atAborted

示例 3

考慮以下示例,我們建立一個無序對映來儲存學生的成績,並使用 at() 函式更新成績。

#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
   unordered_map<string,int> stu_marks = {
      {"Aman", 95},
      {"Vivek", 90},
      {"Sarika", 85},
      {"Ammu", 100}
   };
   stu_marks.at("Aman") = 100;
   stu_marks.at("Vivek") += 95;
   stu_marks.at("Sarika") += 92;
         
   for (auto& i: stu_marks) {
      cout<<i.first<<": "<<i.second<<endl;
   }
   return 0;
}

輸出

以下是上述程式碼的輸出:

Ammu: 100
Sarika: 177
Vivek: 185
Aman: 100

示例 4

以下示例宣告一個無序對映,該對映具有整數型別鍵和字元型別值,並觀察輸出。

#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
   unordered_map<int,char> ASCII = {
      {65, 'a'},
      {66, 'b'},
      {67, 'c'},
      {68, 'd'}
   };
   cout << "Value of key ASCII 66 = " << ASCII.at(66) << endl;
   return 0;
}

輸出

上述程式碼的輸出如下:

Value of key ASCII 66 = b
廣告