In C++, std::swap() exchanges the values of two variables. After the call, a holds what b held and the other way round.
It works on numbers, strings, vectors and most other types. For big containers the swap is fast, because it only exchanges internal pointers.
Syntax
Add #include <algorithm>, then call std::swap(). Start with these two lines.
C++
std::swap(a, b);
std::swap(v1, v2);
Call
What it does
std::swap(a, b);
Swap two variables of the same type.
std::swap(v1, v2);
Swap two whole containers.
The two-argument std::swap() is in <utility> since C++11, and in <algorithm> before that. Including <algorithm> works in all versions.
Library declarations
C++
template<class T>
void swap(T& a, T& b);
Parameters
Parameter
Description
a, b
Required. Two objects of the same type. Both must be writable variables, not constants.
Return Value
Return Value
Description
void
Nothing is returned. The two objects now hold each other's values.
C++ Examples
Example 1 — Swap two numbers
Exchange two integers.
C++
#include <algorithm>
#include <iostream>
int main() {
int a = 3;
int b = 7;
std::swap(a, b);
std::cout << "a=" << a << ", b=" << b << '\n';
return 0;
}
Output
a=7, b=3
How It Works
a and b start with 3 and 7.
std::swap() uses a temporary copy behind the scenes to exchange them.