📜  C++中的unordered_map at()

📅  最后修改于: 2021-05-30 18:09:46             🧑  作者: Mango

先决条件: STL中的无序映射

Unordered_map: unordered_map是一个关联的容器,用于存储由键值和映射值的组合形成的元素。键值用于唯一地标识元素,并且映射值是与键关联的内容。键和值都可以是预定义或用户定义的任何类型。

unordered_map :: at():此函数在C++中的unordered_map返回以元素为键k的值的引用。
句法:

unordered_map.at(k);
Parameter:
It is the key value of the element whose mapped value we want to access.
Return type :
A reference to the mapped value of the element with a key value equivalent

注意:如果不存在密钥,该方法将给出运行时错误。

// C++ program to illustrate 
// std :: unordered_map :: at()
#include 
#include
#include
  
using namespace std;
  
int main()
{
    unordered_map 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'] = "
        <

输出:

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 
#include
#include 
  
using namespace std;
  
// driver code
int main()
{
    // marks in different subjects 
    unordered_map 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<

输出:

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

unordered_map at()与unordered_map运算符()有何不同

  • at()和运算符[]都用于引用给定位置上存在的元素,唯一的区别是,at()抛出了超出范围的异常,而运算符[]显示了未定义的行为,即,如果运算符[]用于找到与key对应的值,如果key在无序映射中不存在,它将首先将key插入映射,然后为该key分配默认值’0’。 。
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”