The std::swap() is a built-in function in C++ stl which swaps the value of two variables.
Syntax:
swap(a, b)
Parameters: The function accepts two mandatory parameters a and b which are to be swapped. The parameters can be of any data-type.
Return Value: The function does not returns anything, it swaps two variables.
Below programs illustrate the swap() function:
Program 1:
// CPP program for illustration // of swap() fucntion #include <bits/stdc++.h> using namespace std; int main() { int a = 10; int b = 20; cout << "Value of a before: " << a << endl; cout << "Value of b before: " << b << endl; // Function to swap variables swap(a, b); cout << "Value of a now: " << a << endl; cout << "Value of b now: " << b << endl; return 0; } |
chevron_right
filter_none
Output:
Value of a before: 10 Value of b before: 20 Value of a now: 20 Value of b now: 10
Program 2:
#include <bits/stdc++.h> using namespace std; int main() { string a = "Geeks"; string b = "function"; cout << "Value of a before: " << a << endl; cout << "Value of b before: " << b << endl; swap(a, b); cout << "Value of a now: " << a << endl; cout << "Value of b now: " << b << endl; return 0; } |
chevron_right
filter_none
Output:
Value of a before: Geeks Value of b before: function Value of a now: function Value of b now: Geeks
Recommended Posts:
- Difference between std::swap and std::vector::swap
- set::swap() in C++ STL
- map::at() and map::swap() in C++ STL
- stack swap() in C++ STL
- forward_list::swap() in C++ STL
- forward_list::swap() in C++ STL
- multimap::swap() in C++ STL
- unordered_multiset swap() in C++ STL
- priority_queue::swap() in C++ STL
- multiset::swap() in C++ STL
- list::swap() in C++ STL
- unordered_set swap() in C++ STL
- queue::swap() in C++ STL
- unordered_multiset swap() function in C++ STL
- multimap swap() function in C++ STL
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



