当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。