C++

At Map C++

The C++ STL library provides us with a map class. Maps are considered associative containers that retain objects in a pair of ordered key values and mapped values. There can never be two mapped values with the same key value. Map class provides many functions but here we will discuss the map.at() function. The mapped element to the key value is passed as the function’s parameter that is referenced using the map.at() function. When we attempt to get to an element that is not inside the container’s range, the map.at() function evaluates the container’s range and throws an exception.

Syntax of map.at() Function

We need to follow the syntax below to implement the map.at() function in C++.

Map_variable.at(key/value pair)

We have used the map object which is named “Map_variable” with the at() function. It returns the element that is directly referenced and points to the specified key value. The data key map mostly depends on the map’s range.  If it is not, there is a possibility that an exception or error will be returned at execution time that signifies that the value is beyond the defined range. Now, we will use this syntax in the C++ codes to show that it’s working.

Example 1: Using map.at() Function

The program is implemented to demonstrate the map.at function. We have linked the at() function with the map() function that takes some input values and shows its functionality. For this, we have filled the program’s header section by importing the map module with another required module for c++. Then, we have called the main() function for the map declaration from the map class. The object of the map is labeled as “MyMap”. We create the list of maps by giving the map key and value.

After this, we invoked the map.at() function which maps the specified string to an integer. Then, we printed the results from the map.at() function from the for loop. The for loop uses the “auto” keyword reference.  The auto keyword indicates that the initializer will automatically remove the variable’s type from the one being declared. The cout statement will print the pairs in the order that is returned from the map.at() function.

#include <iostream>

#include <string>

#include <map>


int main ()

std: :map<std::string,int> MyMap = {

{ “apple”, 0 },

{ "grapes", 0 },

{ "mangoes", 0 } }

MyMap.at("apple")=5;

MyMap.at("grapes")=10;

MyMap.at("mangoes") = 6;

for (auto& m: MyMap) {

std::cout << m.first << ": " << m.second << '\n';}

<strong>return 0;

}

Now, we have the results from the above program that implements the map.at() function. All the specified integers that are in range are displayed against each string.

Example 2: Using map.at() Function for out_of_range Exception

We have discussed through an example program the use of the map.at function in C++. Now, we have implemented another map.at in the program. But this time it will return the value that is presented inside the map and also the out_of_range exception when the key is not specified. As we have to utilize the map.at function, so we have added the map module in the header. Then, we have defined the main function where the “void” is passed as a parameter.

Inside the main function, we have initialized the list constructor by creating the map object as “m1”. The map list has different strings of keys and the integer values against them. Then, we printed the key “i” by passing it through the map.at function. We have employed the try-catch block. In the try block, we have presented the non-existence key in the map.at function. As the key is out of the range, so the try block will throw the error.

#include <iostream>

#include <map>

using namespace std;

int main(void) {


   map<char, int> m1 = {

            {'l', 1},

            {'i', 2},

            {'n', 3},

            {'u', 4},

            {'x', 5},

            };



   cout << "map key value m1['i'] = " << m1.at('i') << endl;



   try {

      m1.at('y');

   } catch(const out_of_range &e) {

      cerr << "Error at " << e.what() << endl;

   }



   return 0;

}

We can visualize from the output screenshot that the map.at() function only returns the keys present in the map. The out-of-range keys throw the error as the error is displayed when we passed the key “y” in the map.at function.

Example 3: Using map.at() Function for Accessing Elements

An element can be accessed using the specified element of digits from the map.at function. Let’s implement this program to accomplish the above statement. We have defined the map module first in the header section as it is required to access the map.at function. Then, we have the main function where the map class initialized the map object as “Map”. With this “Map” object, we have generated the keys of strings and assigned the value of the digit to them. After that, we called the map.at a function with the cout statement and passed the “Example” key as an input.

#include <iostream>

#include <map>

#include <string>

using namespace std;

int main()

{

map<string, int> Map;

Map["My"] = 1;

Map["c++"] = 2;

Map["Map"] = 3;

Map["Example"] = 4;

cout << Map.at("Example");

return 0;

}

The digit element is returned against the specified key in the map.at function. The result gives the value “4” as this digit is assigned to the key element “Example” of a map.

Example 4: Using map.at() Function for Modifying Elements

Let’s consider a simple instance of modifying the value associated with the key value. We have created the list of the map by calling the map class and creating the object “M1”. We have assigned the string value against each key of the map. Then, we have to utilize the map.at function. In the map.at function, we have used the specified keys and assigned the new string values against those keys. Now, these values will be modified with the previous one. With the help of for loop, we have iterated each element from the map and displayed it as an output.

#include <iostream> 

#include <string> 

#include <map> 


using namespace std; 


int main () 

{ 

  map<int,string> M1 = { 

                { 10, "c++"}

                { 20, "java"  }

                { 30, "python" }

                { 40, "csharp" }

                { 50, "OOP"  }}




  M1.at(20) = "Tensorflow";

  M1.at(30) = "Linux";

  M1.at(50) = "Scala";

  cout<<"\nElements:" <<endl; 

  for (auto& x: M1) { 

        cout << x.first << ": " << x.second << '\n'

  } 


  return 0

} 

Notice that values obtained as output have modified the newly assigned string values in the map.at function. The updated values are shown in the snapshot below.

Conclusion

The article is about the map.at function. We have provided the functionality of the map.at() function through its syntax and the example is implemented with C++ compiler. The map.at() function is highly useful as it allows for element accessibility and returns a clear exception or error that describes the situation that arose when the method is being called. Furthermore, we can assign new values against the existence key through the map.at function.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.