Passing Map as Reference in C++ STL
Last Updated :
22 Dec, 2022
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++
#include <iostream>
#include <map>
using namespace std;
void pass_by_reference(map< int , int >& passed_map)
{
passed_map[1] = 200;
passed_map[3] = 300;
}
int main()
{
map< int , int > gfg;
gfg[1] = 25;
gfg[2] = 45;
gfg[3] = 35;
gfg[4] = 65;
gfg[5] = 55;
gfg[6] = 25;
cout << "Original Map\n" ;
cout << "\tKEY\tELEMENT\n" ;
for ( auto i : gfg) {
cout << '\t' << i.first << '\t' << i.second << '\n' ;
}
pass_by_reference(gfg);
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
Share your thoughts in the comments
Please Login to comment...