Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
swap
communitycreator

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

Danil

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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';
}

RELATED TAGS

c++
swap
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring