C++ Algorithm swap_ranges()

C++ Algorithm swap_ranges() exchanges the elements in the range [first1, last2) with the elements present in the range starting from first2.

In short we can say that, swap_ranges() swaps the elements of two sequence, that is each element at a position in the first sequence is replaced by the element at the same position in the second sequence and vice-versa is also possible.

Syntax

Parameter

first1: A forward iterator pointing to the first position of the first range whose elements is to be swapped.

last1: A forward iterator pointing to one past the final position of the first range whose elements are to be swapped.

first2: A forward iterator pointing to the first position of the second range whose elements is to be swapped.

Return value

swap_ranges() returns an iterator pointing to the end of the second range whose elements are to be exchanged.

Complexity

The complexity is linear between first and last. Perform a swap operation for each element in the range.

Data races

The objects in both ranges are modified.

Exception safety

Exception throws if either an element assignment or an operation on iterators throws.

Example 1

Let's see the simple example to swap the element of two vectors with the given range:

Output:

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

In the above example, elements of vector v1 is swapped by vector v2 from range begin to end of v1.

Example 2

Let's see a simple example to exchange the contents of two vectors:

Output:

1 2 3 4 5 5 6 7 8 9 
0 1 2 3 4 6 7 8 9 10

In the above example, swap_range() function swaps the first five element of vector v by the elements of vector c.

Example 3

Let's see a simple example to swap the contents of vector and deque:

Output:

Vector v1 is: ( 0 1 2 3 4 5 ).
Deque d1 is:  ( 6 6 6 6 6 6 ).
After the swap_range vector v1 is: ( 6 6 6 6 6 6 ).
After the swap_range deque d1 is:  ( 0 1 2 3 4 5 ).

In the above example, elements of vector and deque are exchanged to each other.

Example 4

Let's see another simple example:

Output:

s1 = Betty Botter bought some butter
s2 = But she said the butter was bitter
s3 = So she got some better butter
s4 = to make the bitter butter better

Jumble them up!!!
s1 = But she said thught some butter
s2 = Betty Botter boe butter was bitter
s3 = to make the bit better butter
s4 = So she got someter butter better

Next TopicC++ Algorithm




Latest Courses