map operator= in C++ STL

The map::operator= is a built function in C++ STL which assigns contents of a container to a different container, replacing its current content.

Syntax:

map1_name = map2_name

Parameters: The map on the left is the container in which the map on the right is to be assigned by destroying the elements of map1.

Return Value: This function does not return anything.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for illustration of
// map::operator= function
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
  
    // initialize container
    map<int, int> mp, copymp;
  
    // insert elements in random order
    mp.insert({ 2, 30 });
    mp.insert({ 1, 40 });
    mp.insert({ 4, 50 });
  
    // = operator is used to copy map
    copymp = mp;
  
    // prints the elements
    cout << "\nThe map mp is : \n";
    cout << "KEY\tELEMENT\n";
    for (auto itr = mp.begin(); itr != mp.end(); ++itr) {
        cout << itr->first
             << '\t' << itr->second << '\n';
    }
  
    cout << "\nThe map copymap is : \n";
    cout << "KEY\tELEMENT\n";
    for (auto itr = copymp.begin(); itr != copymp.end(); ++itr) {
        cout << itr->first
             << '\t' << itr->second << '\n';
    }
    return 0;
}
chevron_right

Output:
The map mp is : 
KEY    ELEMENT
1    40
2    30
4    50

The map copymap is : 
KEY    ELEMENT
1    40
2    30
4    50

Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.


The function of education is to teach one to think intensively and to think critically

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
C++
Practice Tags :