swap() in C++

Last Updated : 4 Jul, 2026

The swap() function in C++ is a standard library utility used to exchange the values of two objects. It supports most built-in data types, STL containers, and user-defined types.

  • Exchanges the values of two objects without requiring a temporary variable.
  • Works with primitive data types, STL containers, arrays, and custom classes.
C++
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    int a = 1, b = 55;
    cout << a << " " << b << endl;
    
    // swapping the values of a and b
    swap(a, b);
    
    cout << a << " " << b;
    return 0;
}

Output
1 55
55 1

In the above example, we exchange the values of two variables a and b using swap function.

Syntax

The swap() function is defined in the <utility> header file (and is also available through several other standard headers).

swap(a, b);

Parameters

  • a: First object to be swapped.
  • b: Second object to be swapped.

Return Value: The swap() function does not return any value.

Example: The following program demonstrates how to swap two integer variables:

C++
#include <iostream>
#include <utility>
using namespace std;

int main()
{
    int a = 1, b = 55;

    cout << a << " " << b << endl;

    swap(a, b);

    cout << a << " " << b;

    return 0;
}

Output
1 55
55 1

Explanation: The swap() function exchanges the values of a and b without requiring an additional temporary variable.

Swap Two Vectors

The swap function can easily swap elements of two vectors in the same way as other variables.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v1 = {1, 2, 3, 4};
    vector<int> v2 = {6, 7, 8, 9};

    // Swapping the vectors
    swap(v1,