Open In App

Passing Map as Reference in C++ STL

Last Updated : 22 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite: 

Elements in the map are in form of pairs where the first is key and another value, denoting key-value pairs. Also, all the key values are unique means no two elements can have the same key value.

Passing maps by value is a costly task, costly in terms of computation and memory resources. When we pass maps by value, a new copy of the map is created and it takes O(n). When we are using a Map in a Recursive function, using pass-by-value is a nightmare.

Passing Maps by Reference are much faster than passing them by value, and it gives us the freedom to modify the original map inside a function. 

The & (address of) operator is used for passing address of the container which denotes that container are passed by pass-by-reference in a function.

Example:

C++




// C++ Program to implement
// Passing Map As Reference
#include <iostream>
#include <map>
using namespace std;
 
// function that accept map by reference and make changes to
// some of its values
void pass_by_reference(map<int, int>& passed_map)
{
    // change 1st and 3rd value
    passed_map[1] = 200;
    passed_map[3] = 300;
}
 
// main function
int main()
{
    // empty map container
    map<int, int> gfg;
 
    // insert elements in map
    gfg[1] = 25;
    gfg[2] = 45;
    gfg[3] = 35;
    gfg[4] = 65;
    gfg[5] = 55;
    gfg[6] = 25;
 
    // printing original map gfg
    cout << "Original Map\n";
    cout << "\tKEY\tELEMENT\n";
    for (auto i : gfg) {
        cout << '\t' << i.first << '\t' << i.second << '\n';
    }
 
    // passing map to a function by reference
    pass_by_reference(gfg);
 
    // printing map gfg after passing it to a function by
    // reference
    cout << "Map After passing to a function by reference\n";
    cout << "\tKEY\tELEMENT\n";
    for (auto i : gfg) {
        cout << '\t' << i.first << '\t' << i.second << '\n';
    }
 
    return 0;
}


Output

Original Map
    KEY    ELEMENT
    1    25
    2    45
    3    35
    4    65
    5    55
    6    25
Map After passing to a function by reference
    KEY    ELEMENT
    1    200
    2    45
    3    300
    4    65
    5    55
    6    25

Explanation:

  • Firstly we define a function with a return datatype void and take a map<int, int> by reference.
  • This function, pass_by_reference simply modifies the value of keys 1 and 3.
  • After this, inside the main function, we declare a map<int, int>.
  • Then we insert some dummy data in the map.
  • Then we print the original map that we have created.
  • Now we have passed the map to the pass_by_reference function.
  • Finally, we print the map.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads