English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ map at() 函数使用方法及示例

C++ STL map(컨테이너)

C ++ map at()函数用于通过给定的键值访问map中的元素。如果map中不存在所访问的键,则抛出out_of_range异常。

语法

假设键值为k,语法为:

mapped_type& at(const key_type& k);
const mapped_type& at(const key_type& k) const;

参数

k:要访问其map值的元素的键值。

返回值

它使用键值返回对元素map值的引用。

实例1

让我们看一个访问元素的简单示例。

#include <iostream>
#include <string>
#include <map>  
int main ()
{
  map<string,int> m = {
                {"A", 10 },
                {"B", 20 },
                {"C", 30 };
  for (auto& x: m) {
    cout << x.first << ": " << x.second << '\n';
  }
  return 0;
}

출력:

A: 10
B: 20	
C: 30

在上面,at() 함수는 맵의 요소에 접근하는 데 사용되었습니다。

实例2

让我们看一个简单的示例,使用它们的键值添加元素。

#include <iostream>  
#include <string>  
#include <map>  
  
using namespace std;  
int main ()
{
  map<int,string> mymap= {
                { 101, "" },
                { 102, "" },
                { 103, ""} };
  mymap.at(101) = "w3codebox"; 
  mymap.at(102) = ".";
  mymap.at(103) = "com";
//打印键101의 값,即w3codebox
  cout<<mymap.at(101); 
 // 打印键102의 값,即.
  cout<<mymap.at(102);
 // 打印键103의 값,即 com	
  cout<<mymap.at(103);
  return 0;
}

출력:

oldtoolbag.com

在上面的示例中,at() 함수는 초기화 후 연관된 키와 값으로 요소를 추가하는 데 사용되었습니다。

实例3

让我们看一个简单的示例,以更改与键值关联的值。

#include <iostream>  
#include <string>  
#include <map>  
  
using namespace std;  
int main ()
{
  map<int,string> mymap= {
                { 100, "Nikita"},
                { 200, "Deep"  },
                { 300, "Priya" },
                { 400, "Suman" },
                { 500, "Aman"  }};
                
  cout<<"元素是:" <<endl;
  for (auto& x: mymap) {
    	cout << x.first << ": " << x.second << '\n';
  }
  mymap.at(100) = "Nidhi"; // 키100의 값이 Nidhi로 변경되었습니다
  mymap.at(300) = "Pinku"; // 키300의 값이 Pinku로 변경되었습니다
  mymap.at(500) = "Arohi"; // 키500의 값이 Arohi로 변경되었습니다
  
  
  cout<<"\n更改后元素是:" <<endl;
  for (auto& x: mymap) {
    	cout << x.first << ": " << x.second << '\n';
  }
  
  return 0;
}

출력:

元素是:
100: Nikita
200: Deep
300: Priya
400: Suman
500: Aman
更改后元素是:
100: Nidhi
200: Deep
300: Pinku
400: Suman
500: Arohi

在上面的示例中,at() 함수는 그 키와 연관된 값을 변경하는 데 사용되었습니다。

实例4

让我们看一个简单的示例来处理“超出范围”?例外。

#include <iostream>  
#include <string>  
#include <map>  
  
using namespace std;  
int main ()
{
  map<char,string> mp= {
                { 'a',"Java"},
                { 'b', "C++"  },
                { 'c', "Python" }};
            
    cout<<endl<<mp.at('a');
    cout<<endl<<mp.at('b');
    cout<<endl<<mp.at('c');
    
    try {
        mp.at('z'); 
          // map에 z 값이 없기 때문에 예외가 발생합니다
        
    }
        cout<<endl<<"Out of Range Exception at "<<e.what();
}

출력:

Java
C++
Python
Out of Range Exception at map::at

위의 예제는 z 값이 없는 map에서 out_of_range 예외를 발생시킵니다.

C++ STL map(컨테이너)