Javatpoint Logo
Javatpoint Logo

C++ Algorithm iter_swap()

C++ Algorithm iter_swap() exchanges the elements pointed to by two iterators a and b.

Syntax

Parameter

a: One of the forward iterator whose value is to be exchanged.

b: Second of the forward iterator whose value is to be exchanged.

Return value

None

Complexity

Constant

Data races

The objects pointed to by both iterators are changed.

Exception safety

Throws an exception if swap() function has an exception.

Please note that invalid parameters cause an undefined behavior.

Example 1

Let's see the simple example to demonstrate the use of iter_swap():

Output:

v1: 1, 6, 3, 
v2: 4, 5, 2, 

Example 2

Let's see another simple example:

Output:

9 1 2 3 4 5 6 7 8 0  

In the above example, we have swapped elements from v1 with the help of two iterators, one of them pointing at the beginning of v1 and the other one pointing at the end of v1.

Example 3

Let's see another simple example to swap the odd places of vector to odd paces of array:

Output:

Vector : 0   0   0   0   0   0   0   0   0   0   
Array  : 1   2   3   4   5   6   7   8   9   10   

Swapping odd places of vector with odd places of array

Vector : 0   2   0   4   0   6   0   8   0   10   
Array  : 1   0   3   0   5   0   7   0   9   0  

Example 4

Let's see another simple example:

Output:

Here are the contents of v1:
1 2 3 4 5 
Here are the contents of v2:
2 4 6 8 10 

First we swap the end values in v1.
Here are the contents of the revised v1:
5 2 3 4 1 

Then we swap the middle values in v1 and v2.
Here are the contents of the revised v1:
5 2 6 4 1 
Here are the contents of the revised v2:
2 4 3 8 10  

The above example illustrates the use of the iter_swap() algorithm to swap integer values that are pointed to by two different iterators that may point into the same vector of integers, or into two different vectors of integers.

Example 5

Let's see another example to illustrate the use of iter_swap():

Output:

Before calling iter_swap
Numbers { 1 1 2 3 5 8 13 21  }

After calling iter_swap
Numbers { 21 1 2 3 5 8 13 1  }

Next TopicC++ Algorithm





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA