當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C++ unordered_map at()用法及代碼示例


先決條件: STL中的無序Map

Unordered_map:unordered_map是關聯的容器,用於存儲由鍵值和映射值的組合形成的元素。鍵值用於唯一地標識元素,並且映射值是與鍵關聯的內容。鍵和值都可以是預定義或用戶定義的任何類型。

unordered_map::at():C++中的此函數unordered_map以該元素為鍵k返回對該值的引用。句法:


unordered_map.at(k);
參數:
It is the key value of the element whose mapped value we want to access.
返回類型:
A reference to the mapped value of the element with a key value equivalent

注意:如果不存在 key ,該方法將給出運行時錯誤。

// C++ program to illustrate  
// std::unordered_map::at() 
#include<iostream>  
#include<string> 
#include<unordered_map> 
  
using namespace std; 
  
int main() 
{ 
    unordered_map<string,int> mp = { 
                            {"first",1}, 
                            {"second",2}, 
                            {"third",3}, 
                            {"fourth",4} 
    }; 
                                      
    // returns the reference i.e. the mapped 
    // value with the key 'second' 
    cout<<"Value of key mp['second'] = "
        <<mp.at("second")<<endl; 
      
    try 
    { 
        mp.at(); 
    }  
  
    catch(const out_of_range &e) 
    { 
        cerr << "Exception at " << e.what() << endl; 
    }  
      
      
    return 0; 
}

輸出:

Value of key mp['second'] = 2
Exception at _Map_base::at

實際應用:std::unordered_map::at()函數可用於訪問映射值,從而可以進行編輯,更新等。

// CPP program to illistrate 
// application of this function 
// Program to correct the marks  
// given in different subjects 
#include<iostream>  
#include<string> 
#include<unordered_map>  
  
using namespace std; 
  
// driver code 
int main() 
{ 
    // marks in different subjects  
    unordered_map<string,int> my_marks = { 
                    {"Maths", 90}, 
                    {"Physics", 87}, 
                    {"Chemistry", 98}, 
                    {"Computer Application", 94} 
                    }; 
          
                                      
        my_marks.at("Physics") = 97; 
        my_marks.at("Maths") += 10; 
        my_marks.at("Computer Application") += 6; 
          
        for (auto& i:my_marks) 
        { 
            cout<<i.first<<":"<<i.second<<endl; 
        } 
      
      
      
    return 0; 
}

輸出:

Computer Application:100
Chemistry:98
Physics:97
Maths:100

unordered_map at()與unordered_map operator()有何不同

  • at()和operator []都用於引用給定位置上存在的元素,唯一的區別是at()拋出了超出範圍的異常,而operator []顯示了未定義的行為。



注:本文由純淨天空篩選整理自akash1295大神的英文原創作品 unordered_map at() in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。