Passing Map as Reference in C++ STL
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.
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
- 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.
Please Login to comment...