What is the std::swap function in C++?

std::swap() is a built-in function in C++'s Standard Template Library. The function takes two values as input and swaps them.

Take a look at the signature of the std::swap() function below:

Function signature of std::swap

Syntax

template<class T>
constexpr void swap(T& a, T& b); // Swap the values a and b
template< class T2, std::size_t N >
constexpr void swap( T2 (&a)[N], T2 (&b)[N]); // Swaps the arrays a and b.

Header file

To use the swap() function, we need to include the header file <utility> in our C++ program.

Code

Example 1 - Using std::swap()

// The following header file needs to be included to use std::swap()
#include <utility>
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 5;
// before
std::cout << "a: " << a << "\tb: " << b << '\n';
swap(a, b);
// after
std::cout << "a: " << a << "\tb: " << b << '\n';
}

Example 2 - Using std::swap() with arrays

// The following header file needs to be included to use std::swap()
#include <utility>
#include <iostream>
using namespace std;
int main() {
int even[] = {2, 4, 6, 8, 10};
int odd[] = {1, 3, 5, 7, 9};
// before
std::cout << "odd: ";
for(int x: odd) {
std::cout << x << ' ';
}
std::cout << '\n';
std::cout << "even: ";
for(int x: even) {
std::cout << x << ' ';
}
std::cout << "\n\n";
// swapping arrays odd and even
swap(odd, even);
// after
std::cout << "odd: ";
for(int x: odd) {
std::cout << x << ' ';
}
std::cout << '\n';
std::cout << "even: ";
for(int x: even) {
std::cout << x << ' ';
}
std::cout << '\n';
}