This post will discuss swap operation on a vector in C++.

Here’s a three-line implementation of the swap function in C using pointers.

 
Let’s discuss various methods to do this in C++:

1. Using std::move function

We can use std::move introduced by the C++11 to swap two objects, as shown below:

Download  Run Code

Output:

0 1 3 2 4

2. Using std::swap function

The standard solution is to use the std::swap algorithm defined in the <utility> header (in C++11). It works by swapping the values of two objects.

Download  Run Code

Output:

0 1 3 2 4

3. Using std::iter_swap function

Another alternative is to use the std::iter_swap algorithm defined in the <algorithm> header. It works by swapping the values of objects pointed to by specified iterators.

Download  Run Code

Output:

0 1 3 2 4

That’s all about swap operation on a vector in C++.