Javatpoint Logo
Javatpoint Logo

C++ multimap swap() function

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

Syntax

Parameter

x: multimap container to exchange the contents with.

Return value

None

Complexity

Constant.

Iterator validity

All iterators, references and pointers referring to elements in both containers remain valid, but now are referring to elements in the other container, and iterate in it.

Data races

Both the container and x are modified.

Exception safety

No effect on container if exception is thrown.

Example 1

Let's see the simple example to swap the element of one multimap to another:

Output:

Multimap m2 contains following elements
a = 1
b = 2
b = 4
c = 3
c = 5

In the above example, multimap 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 multimaps:

Output:

multimap1 contains:
a => 110
a => 330
b => 220
multimap2 contains:
x => 100
x => 200

In the above example, contents of two multimaps i.e. multimap1 and multimap2 are exchanged to each other.

Example 3

Let's see a simple example to swap the contents of two multimaps:

Output:

multimap1:
	KEY	ELEMENT
	1	x
	2	y
	2	z
multimap2:
	KEY	ELEMENT
	1	a
	2	b
	2	c
	4	d

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

Example 4

Let's see a simple example:

Output:

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

Contents of m1: 

m1 is now empty.

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

Next TopicC++ multimap




Help Others, Please Share

facebook twitter pinterest