C++ Program to Replace Elements in a Dictionary


As a form of data structure, dictionaries are a common choice in different computer languages. One kind of quicker data structure for storing data with keys and values is a dictionary. For the keys to quickly search for certain components in almost real-time, it retains the key-value combination there. A data structure that resembles dictionaries is part of the C++ STL language standard. This data structure is referred to as a "map". The map generates a pair of keys and values of any type (the type must be defined before compilation as we are using C++). This section will demonstrate how to replace elements in a map or dictionary, in C++.

Let's start by looking at the map data structure's definition. Two distinct datatypes are required in the templates. The required libraries and syntax are shown below −

Syntax to define Map Data Structure

#include <map>
map<type1, type2> mapVariable;

To use the map data structure in this case, we must import the "map" library. For this, data types 1 and 2 are required. The value parameter's data type is type2, but the key parameter's data type is type1. Here, mapVariable is the object that is of type map class. Now let's look at how to accomplish this using C++ maps.

By accessing an existing key or a new key, we can add value to the map data structure. We must change an existing value for a specific key since we are talking about replacing values here. In the same manner, as array indexing notations, the key will be utilized inside square brackets. Let's look at this statement's syntax −

Syntax to replace elements inside the map

mapVariable [<the key value>] = <the new value>;

Algorithm

  • An already created dictionary or map D

  • already existing key value k

  • the value v for the new key k

  • replace like D[ k ] = v

  • return D

Example

#include <iostream> 
#include <map> 
using namespace std;

void display( map <string, int>& givenMap ){
   for ( auto& it : givenMap ) {
      cout << "Key: " << it.first << ", value: " << it.second << endl;
   }
}
   
int main(){ 
   map<string, int> givenMap;
   
   givenMap = { { "Lili", 25 },
        { "Alice", 50 },
        { "Manoj", 75 },
        { "Sumit", 100 },
        { "Bob", 125 }
   };
   
   cout << "Before updation: " << endl;
   display( givenMap );
  
   cout << "After Updation: " << endl;
   
   //update the value of Sumit to 1890
   givenMap[ "Sumit" ] = 1890; 
   display( givenMap );
}

Output

Before updation: 
Key: Alice, value: 50
Key: Bob, value: 125
Key: Lili, value: 25
Key: Manoj, value: 75
Key: Sumit, value: 100
After Updation: 
Key: Alice, value: 50
Key: Bob, value: 125
Key: Lili, value: 25
Key: Manoj, value: 75
Key: Sumit, value: 1890

By using the key parameter in this technique, we were able to correctly replace a value. This method, nevertheless, might not always be appropriate. This method has a significant flaw in that the specified key might not be present in the map. However, by utilizing this procedure, a new key with the specified value will be inserted. In the next approach, we will see another solution to replace the element only after searching for that key.

Replacing after searching

Using the map object's find() function, one can determine whether a key is contained within a map. If the key exists, it will provide a pointer reference; if not, it will return the map's end() pointer, which indicates that the element is not present in the map.

Let us see the algorithm and implementation for a better understanding.

Algorithm

  • An already created dictionary or map D

  • already existing key value k

  • the value v for the new key k

  • create an iterator object itr to get the pointer for the key-value pair

  • call find() method for the dictionary D into itr

  • if itr is not the end of D, that signifies the key is present, then

    • put v into itr

  • end if

Example

#include <iostream> 
#include <map> 
using namespace std;

void display( map <string, int>& givenMap ){
   for ( auto& it : givenMap ) {
      cout << "Key: " << it.first << ", value: " << it.second << endl;
   }
}

void replaceElement( map <string, int>& givenMap, string givenKey, int newValue ){
   map <string, int>::iterator itr;
   itr = givenMap.find( givenKey );
   if( itr != givenMap.end() ){   // when item has found
      itr->second = newValue;
   }
}
   
int main(){ 
   map<string, int> givenMap;
   
   givenMap = { { "Lili", 25 },
        { "Alice", 50 },
        { "Manoj", 75 },
        { "Sumit", 100 },
        { "Bob", 125 }
   };
   
   cout << "Before updation: " << endl;
   display( givenMap );
  
   cout << "After Updation: " << endl;
   
   //replace the value of Sumit to 1890
   replaceElement( givenMap, "Sumit", 1890 );
   
   //replace the value of Alice to 5017
   replaceElement( givenMap, "Alice", 5017 );
   display( givenMap );
}

Output

Before updation: 
Key: Alice, value: 50
Key: Bob, value: 125
Key: Lili, value: 25
Key: Manoj, value: 75
Key: Sumit, value: 100
After Updation: 
Key: Alice, value: 5017
Key: Bob, value: 125
Key: Lili, value: 25
Key: Manoj, value: 75
Key: Sumit, value: 1890

In this method, the map, the current key, and the newValue are all inputs to the replaceElement function. Find the key after that. If it's there, update the value; if not, exit the method immediately. Therefore, by utilizing this method, we can only update an existing entry in the map rather than adding a new one.

Conclusion

In this article, we learned how to use a key to replace specific map items. In the first method, the element is successfully replaced by the direct assigning technique, which can also add a new element if the key is missing. The second strategy eliminates this problem by starting with a straightforward search. We may occasionally see that the second way requires more time because we have to look for the key and then replace it. As a result, searching now requires more time than before. But the finding is also being carried out inherently in the first technique. The data structure will function in constant time because it uses hashing-based approaches (in most cases).

Updated on: 13-Dec-2022

790 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements