Javatpoint Logo
Javatpoint Logo

C++ map operator=() function

There are following three uses of operator=() in a map:

  1. Operator=() is used to assign new contents to the map container by replacing its old content (or copy the contents) and modifies size if necessary.
  2. Operator=() is used to move the contents of one map container into another and modifies size if necessary.
  3. Operator= is used to copy the elements from the initializer list to map container.

Syntax

copy (1):- Copies all the elements from x into the map container.

move (2):- Moves the contents of x into the map container.

initializer_list (3):- Copies the elements of il into the map container.

Parameter

x: A map object with the same type.

il: An initializer list object.

Return value

this pointer.

Example 1

Let's see a simple example to copy the content of one map to another.

Output:

Map m1 contains following elements
a = 10
b = 20
c = 30

After copying the elements from m1 to m2... 

Map m2 contains following elements
a = 10
b = 20
c = 30

In the above example, operator=() function is used to copy the content of one map m1 to another map m2.

Example 2

Let's see a simple example to move the elements of one map to another.

Output:

Map m1 contains following elements
a = 1
b = 2
c = 3

After moving the elements from m1 to m2... 

Map m2 contains following elements
a = 1
b = 2
c = 3

In the above example, operator=() function is used to move the content of one map m1 to another map m2.

Example 3

Let's see a simple example to copy the content from the initializer list to map.

Output:

Map contains the following elements
a = 100
b = 200
c = 300
d = 400

In the above example, operator=() is used to copy the content from initializer list to map m.

Example 4

Let's see a simple example.

Output:

Size of first: 0
Size of second: 3

In the above example, first it will calculate the size of the empty map fisrt then add some elements to the first map and copy to second map.

Next TopicC++ Map



Please Share

facebook twitter google plus pinterest