C++ algorithm swap() function
Example
Swap the values of two variables:
int a = 10, b = 25;
cout << "Before: a = " << a << " | b = " << b << "\n";
swap(a, b);
cout << "After: a = " << a << " | b = " << b << "\n";
Try it Yourself »
Definition and Usage
The swap()
function swaps the values of two variables, such that each variable has the value that the other variable had before the swap occurred.
Both variables must have the same data type.
Syntax
swap(a, b);
Parameter Values
Parameter | Description |
---|---|
a | Required. Any variable. |
b | Required. A variable with the same data type as a. |
Related Pages
Read more about data structures in our Data Structures Tutorial.
Read more about iterators in our Iterators Tutorial.
Read more about algorithms in our Algorithms Tutorial.