Standard Library[lib]
std::swap in C++: how to swap two values, with examples
- Section
- Standard Library [lib]
- Standard
- C++17
- Compilers
- MSVC 19.44, Clang 19.1 (MSVC STL), GCC 16.2, Clang 23.1 (libc++)
- Published
- Length
- 7 min read
Abstract
std::swap(a, b), from <utility>, exchanges the values of two objects of the same type: it moves a into a temporary, b into a, and the temporary into b. It swaps numbers, elements of a vector or array, strings, whole vectors (by trading their buffers, without touching an element) and your own classes. A hand-written swap needs reference parameters, or it swaps copies; for your own class, call using std::swap; swap(a, b); so the class's own swap is found.

std::swap exchanges the values of two objects of the same type: after std::swap(a, b), a holds what b held and b holds what a held. It is declared in the header <utility> and works on numbers, strings, containers and your own types. For a vector it trades the two buffers instead of copying the elements.
The smallest whole program swaps two players’ scores and their names:
#include <iostream>
#include <string>
#include <utility>
int main() {
int a = 3, b = 8;
std::string first = "Ana", second = "Ben";
std::cout << a << ' ' << b << '\n';
std::cout << first << ' ' << second << '\n';
std::swap(a, b);
std::swap(first, second);
std::cout << a << ' ' << b << '\n';
std::cout << first << ' ' << second << '\n';
}— end example]
It printed:
3 8
Ana Ben
8 3
Ben Ana— end example]
The samples on this page are C++17, built with MSVC 19.44, Clang 19.1 (MSVC STL), GCC 16.2 and Clang 23.1 (libc++), and all four printed the same for every one. Since When lists which standard added each feature.
How do you swap two numbers in C++?
Write std::swap(a, b);. By hand, a swap is three assignments through a third variable, which is what the library does for you:
int tmp = a; // tmp: 3
a = b; // a: 8
b = tmp; // b: 3— end example]
Tutorials also teach swaps “without a temporary”. They are exercises, not code to keep. Adding and subtracting (a = a + b; b = a - b; a = a - b;) can overflow, which for a signed int is undefined behavior: the standard places no requirement on what the program then does.
The XOR version, xor_swap(int& x, int& y) doing x ^= y; y ^= x; x ^= y;, swapped 3 and 8 correctly, but xor_swap(n, n), with both arguments the same variable, turned n from 5 into 0 on all four compilers. Written as a function on two int& the same way, the add-and-subtract version printed the same: 8 3, then 0.
How does std::swap work?
It moves a into a temporary, moves b into a, then moves the temporary into b. A move hands an object’s contents to another object instead of copying them; move semantics and std::move explains how.

For an int a move just copies the number; the saving is for types that own memory, such as a string or a vector. Score, a small type that counts its own copies and moves, recorded one move construction, two move assignments and no copies for one std::swap, on all three standard libraries.
std::swap takes both arguments as T& with a single T ([utility.swap]), so the two must have the same type:
int i = 1;
double d = 2.5;
std::swap(i, d); // int and double: does not compile— end example]
All four compilers rejected it. Clang 19.1’s note names the cause:
note: candidate template ignored: deduced conflicting types for parameter '_Ty' ('int' vs. 'double')— end example]
How do you swap two elements of a vector or array?
Pass the two elements to std::swap. The same call works on a built-in array, a std::array and two characters of a string (print writes the values on one line):
std::vector<int> v = {3, 8, 5};
std::swap(v[0], v[2]);
print(v); // 5 8 3
int scores[] = {3, 8, 5};
std::swap(scores[0], scores[2]);
std::array<int, 3> points = {3, 8, 5};
std::swap(points[0], points[2]);
print(scores); // 5 8 3
print(points); // 5 8 3
std::string name = "Ana";
std::swap(name[0], name[2]);
std::cout << name << '\n'; // anA— end example]
All four printed what the comments show.
What does vector::swap do?
a.swap(b) trades the two vectors’ storage in constant time, and std::swap(a, b) on two vectors does the same. No element is copied or moved, however long the vectors are, and their sizes may differ. A pointer or iterator to an element keeps pointing at that element, which now lives in the other vector. Two teams’ scores, held as Scores:
std::vector<Score> a = {3, 8, 5};
std::vector<Score> b = {7, 2, 9, 4, 6};
// ...
const auto* first = &a[0];
a.swap(b);
std::cout << a.size() << ' ' << b.size() << '\n'; // 5 3
std::cout << (first == &b[0]) << '\n'; // true
std::cout << first->points << '\n'; // 3— end example]
Score counted no copy and no move after either call, on all three standard libraries. For the operations that do move a vector’s elements, see std::vector: size, capacity and reallocation.
Two std::strings swap with the same two calls, also in constant time, and trade their contents, but pointers and iterators into a string may no longer be valid afterwards. In the samples, a pointer followed the characters of a long string and not of a short one.
Why does my own swap function swap nothing?
Because its parameters are passed by value: the function receives copies of the caller’s variables, swaps the copies, and the originals stay as they were. Take the parameters by reference (int&) so they name the caller’s variables:
void swap_copy(int x, int y) { // x and y are copies
int tmp = x;
x = y;
y = tmp;
}
void swap_ref(int& x, int& y) { // x and y are the caller's
int tmp = x;
x = y;
y = tmp;
}
// ...
int a = 3, b = 8;
swap_copy(a, b);
std::cout << a << ' ' << b << '\n'; // 3 8: unchanged
swap_ref(a, b);
std::cout << a << ' ' << b << '\n'; // 8 3— end example]
No compiler warned about swap_copy at /W4 or -Wall -Wextra, so the mistake shows only in the output. Pass by value or const reference covers which parameter type to use when.
How do you swap two objects of your own class?
std::swap already works on any class that can be move constructed and move assigned. When your class can swap more cheaply member by member, give it a swap of its own that is not a member (here a friend defined inside the class), and call it the way generic code does: using std::.
class Team {
public:
// ...
void swap(Team& other) noexcept {
name_.swap(other.name_);
scores_.swap(other.scores_);
}
friend void swap(Team& x, Team& y) noexcept {
++team_swaps;
x.swap(y);
}
private:
std::string name_;
std::vector<int> scores_;
};
// ...
using std::swap;
swap(t1, t2); // Team's own swap
// ...
using std::swap;
swap(a, b); // no swap of its own for int: std::swap— end example]
The unqualified call finds the friend through argument-dependent lookup (ADL), which also searches the arguments’ own classes and namespaces, and the using line makes std::swap a candidate too. For two Teams overload resolution prefers the friend, an exact match that is not a template; for two ints ADL finds nothing, so std::swap runs.
All four printed Ben's team, Ana's team and Team's swap ran 1 time, then 8 3 for the ints. Written as std::swap(t1, t2), the call skipped Team’s function and fell back to the three moves: the teams swapped back and the count stayed at 1.
A swap must not fail, so mark it noexcept, as the C++ Core Guidelines advise in C.83 to C.85.
A swap cheat sheet
| To swap | Write |
|---|---|
| Two variables | std::swap(a, b); |
| Two elements | std:: |
| Two vectors | a.swap(b); or std::swap(a, b);: no element copied |
| Two strings | s1.swap(s2); or std::swap(s1, s2); |
| In your own function | reference parameters: int& x, int& y |
| Two objects of your class | a noexcept friend swap, called as using std:: |
| A new value, keeping the old | std:: returns the old value (since C++14) |
The other containers and the rest of the library are in Standard library.
Questions
Which header is std::swap in?
Include <utility>. std::swap has been declared there since C++11; before C++11 it was in <algorithm>.
How do you swap two strings in C++?
Call std::swap(s1, s2) or the member function s1.swap(s2). Both trade the two strings’ contents, and the member runs in constant time whatever their lengths. Pointers and iterators into either string may no longer be valid afterwards, so take them again after the swap.
Can std::swap swap two arrays?
Yes, two built-in arrays of the same element type and size, element by element: std::swap(a, b) on two int arrays of three elements left each holding the other’s values. Two std::array objects of the same type swap the same way. Arrays of different sizes cannot be swapped.
What is the difference between std::swap and std::exchange?
std::swap(a, b) trades the values of two objects. std::exchange(obj, new_value), from <utility> since C++14, puts a new value in one object and returns the value it held before. Use exchange when you replace a value and still need the old one.
Can std::swap throw?
For most types, only if the type’s move constructor or move assignment can throw: the general std::swap is noexcept exactly when both are. std::vector and std::string have their own overloads, which cannot throw with the default allocator, and swapping two built-in values cannot throw either.
How do you swap two numbers without a third variable?
With arithmetic (a = a + b; b = a - b; a = a - b;) or with XOR (a ^= b; b ^= a; a ^= b;), but neither belongs in real code. Adding can overflow, which for a signed int is undefined behavior, and both tricks left the value at 0 when a variable was swapped with itself. Write std::swap(a, b) instead.
Sources
- std::swapcppreference.com
- [utility.swap] swapC++ standard working draft
- std::vector::swapcppreference.com
- std::basic_string::swapcppreference.com
- std::exchangecppreference.com
- C++ Core Guidelines: C.83 to C.85, swapStandard C++ Foundation