Related Articles

Related Articles

swap() in C++
  • Difficulty Level : Basic
  • Last Updated : 01 May, 2019

The function std::swap() is a built-in function in the C++ Standard Template Library (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 return anything, it swaps the values of the two variables.

Programs below illustrate the swap() function:



Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for illustration of swap() function
#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;
  
    // swap values of the variables
    swap(a, b);
    cout << "Value of a now: " << a << endl;
    cout << "Value of b now: " << b << endl;
    return 0;
}

chevron_right


Output:

Value of a before: 10
Value of b before: 20
Value of a now: 20
Value of b now: 10

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

#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


Output:

Value of a before: Geeks
Value of b before: function
Value of a now: function
Value of b now: Geeks

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :