C++ map swap() function

C++ map swap() function is used to swap (or exchange) the contents of two maps but both the maps must be of the same type although sizes may differ.

Syntax

Parameter

x: The map container to exchange the contents with.

Return value

None

Example 1

Let's see a simple example to swap the element of one map to another.

Output:

Map contains following elements
a = 1
b = 2
c = 3
d = 4
e = 5

In the above example, map m1 has five elements and m2 is empty. When you swap m1 to m2 then all the elements of m1 is swapped to m2.

Example 2

Let's see a simple example to exchange the contents of two maps.

Output:

map1 contains:
a => 110
b => 220
c => 330

map2 contains:
x => 100
y => 200

In the above example, contents of two maps i.e. map1 and map2 are exchanged to each other.

Example 3

Let's see a simple example to swap the contents of two maps.

Output:

map1:
	KEY	ELEMENT
	5	w
	6	x
	7	y
map2:
	KEY	ELEMENT
	1	a
	2	b
	3	c
	4	d

In the above example, another form of swap() function is used to swap the contents of two maps.

Example 4

Let's see a simple example.

Output:

Exchange m1 and m2.
Contents of m2: 
  A, 100
  B, 200
  G, 300

Contents of m1: 
m1 is now empty.

In the above example, contents of map m1 are swapped to map m2 and after swapping m1 map have been cleared.

Next TopicC++ Map



Latest Courses