C++ map update – Simple program example to update value in map. To update an existing value in the map, first we will find the value with the given key using map::find() function. If the key exists, then will update it with new value.

C++ map update example

This example program has a key value pair in a std::map as below.

1," Peter "
2," Lisa "
3," Danish "
4," Linda "

The program will find the the value with given key e.g. 3 and update it with the value “John”.

As an output, this C++ Program will show the list before and after update value.


/*-------------------------------------------------------
*  C++ Example - Update value in map
* 
*/

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

int main(){

      /* Create a hash map - int as key and string as value */
      std::map<int, std::string> m;

      /* Insert some elements ( key value pair) in the hash map */
      m.insert ( std::pair<int,string>(1,"Peter") );
      m.insert ( std::pair<int,string>(2,"Lisa") );
      m.insert ( std::pair<int,string>(3,"Danish") );
      m.insert ( std::pair<int,string>(4,"Linda") );

      /* Print the elements from hash map */

      std::cout << "map Contains:\n";   
      std::map<int,string>::iterator itr;
      for( itr = m.begin(); itr != m.end(); ++itr){

            cout << "Key => " << itr->first << ", Value => " << itr->second.c_str() << endl;      

      }    


      /* Update the value of an existing key */
      //updating the the value of key = 3

      itr = m.find(3);

      if (itr != m.end())
            itr->second = "John";

      std::cout << "Updated map Contains:\n";  


      for( itr = m.begin(); itr != m.end(); ++itr){
            cout << "Key => " << itr->first << ", Value => " << itr->second.c_str() << endl;      

      }  

      return 0;

}

Output:
map Contains:
Key => 1, Value => Peter
Key => 2, Value => Lisa
Key => 3, Value => Danish
Key => 4, Value => Linda

Updated map Contains:
Key => 1, Value => Peter
Key => 2, Value => Lisa
Key => 3, Value => John
Key => 4, Value => Linda

Related Posts