map::at() in C++ STL

C++Server Side ProgrammingProgramming

In this article we will be discussing the working, syntax and examples of map::at() function in C++ STL.

What is a Map in C++ STL?

Maps are the associative container, which facilitates to store the elements formed by a combination of key value and mapped value in a specific order. In a map container the data is internally always sorted with the help of its associated keys. The values in the map container are accessed by its unique keys.

What is a map::at()?

map::at() function is an inbuilt function in C++ STL, which is defined in  header file. at() is used to access a specific element of the associated map container. This function returns a reference to the specific value which is associated with the key.

If there is a case when the key is not matching to any key of the map container then, the function throws an out_of_range exception.

Syntax

map_name.at(key& k);

Parameters

The function accepts one parameter i.e.

Return value

This function returns a reference to the value associated with key k which we are looking for.

Example

Input

std::map<int> mymap;
mymap.insert({‘a’, 10});
mymap.insert({‘b, 20});
mymap.insert({‘c, 30});
mymap.at(‘b’);

Output

b:20

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main() {
   map<int, int> TP_1;
   map<int, int> TP_2;
   TP_1[1] = 10;
   TP_1[2] = 20;
   TP_1[3] = 30;
   TP_1[4] = 40;
   TP_2[5] = 50;
   TP_2[6] = 60;
   TP_2[7] = 70;
   cout<<"Elements at TP_1[1] = "<< TP_1.at(1) << endl;
   cout<<"Elements at TP_1[2] = "<< TP_1.at(2) << endl;
   cout<<"Elements at TP_1[3] = "<< TP_1.at(3) << endl;
   cout<<"\nElements at TP_2[7] = "<< TP_2.at(7) << endl;
   cout<<"Elements at TP_2[5] = "<< TP_2.at(5) << endl;
   return 0;
}

Output

Elements at TP_1[1] = 10
Elements at TP_1[2] = 20
Elements at TP_1[3] = 30
Elements at TP_1[7] = 70
Elements at TP_1[5] = 50
raja
Published on 15-Apr-2020 12:57:37
Advertisements