How to Use swap in C++: Syntax and Examples
In C++, you can use the
std::swap function to exchange the values of two variables efficiently. Include the <utility> header and call std::swap(a, b) where a and b are the variables you want to swap.Syntax
The std::swap function swaps the values of two variables. It requires including the <utility> header. The syntax is:
std::swap(a, b);- swaps the values ofaandb.
Here, a and b must be variables of the same type or compatible types.
cpp
std::swap(variable1, variable2);
Example
This example shows how to swap two integers using std::swap. It prints the values before and after swapping.
cpp
#include <iostream> #include <utility> // for std::swap int main() { int a = 5; int b = 10; std::cout << "Before swap: a = " << a << ", b = " << b << '\n'; std::swap(a, b); std::cout << "After swap: a = " << a << ", b = " << b << '\n'; return 0; }
Output
Before swap: a = 5, b = 10
After swap: a = 10, b = 5
Common Pitfalls
Common mistakes when using std::swap include:
- Not including the
<utility>header, causing a compile error. - Trying to swap variables of incompatible types.
- Swapping pointers or references without understanding what is actually swapped (the pointer value, not the pointed data).
Also, swapping const variables is not allowed because std::swap requires modifiable lvalues.
cpp
#include <iostream> //#include <utility> // Missing this causes error int main() { int a = 1; double b = 2.0; // std::swap(a, b); // Error: incompatible types const int c = 3; int d = 4; // std::swap(c, d); // Error: cannot swap const variable return 0; }
Quick Reference
Tips for using std::swap:
- Always include
<utility>. - Use it to swap values of the same or compatible types.
- Works with built-in types and user-defined types that have a swap overload.
- Swapping is done by exchanging values, not copying.
Key Takeaways
Use
std::swap from <utility> to exchange values of two variables.Both variables must be modifiable and of the same or compatible types.
Do not forget to include the
<utility> header to avoid compilation errors.Swapping pointers swaps the pointer values, not the data they point to.
You cannot swap const variables because they cannot be modified.