The Wayback Machine - https://web.archive.org/web/20241223175605/https://www.geeksforgeeks.org/swap-in-cpp/
Open In App

swap() in C++

Last Updated : 11 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The std::swap() is a built-in function in the C++ STL which swaps the value of two variables. This function supports almost every data type available in C++, whether it is a primitive type such as int, char, etc. or STL containers such as vector, maps, etc.

It is defined inside <algorithm> header file.

Syntax

std::swap(a, b)

Parameters

  • a: First variable which is to be swapped.
  • b: Second variable which is to be swapped.

Return Value

  • The function does not return any value.

To learn how to use this function and its applications in C++, check out the C++ Course for detailed explanations and examples.

Examples of std::swap()

The following examples demonstrate how to use swap function in C++.

Example 1: Swapping the Values of Two Integers

C++
// C++ program for swapping two integers using
// std::swap function
#include <bits/stdc++.h>
using namespace std;

int main() {
    int a = 10;
    int b = 20;

    // Swap values of a and b
    swap(a, b);
  
    cout << "a = " << a << "\t" << "b = " << b;
    return 0;
}

Output
a = 20    b = 10

Time Complexity: O(1)
Auxiliary Space: O(1)

Example 2: Swap All Elements of Two Vectors

C++
// C++ Program to swap the contents of two
// vectors with each other
#include <bits/stdc++.h>
using namespace std;

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

    // Swapping the vectors
    swap(vec1, vec2);

    // Printing the vectors
    cout << "vec1: ";
    for (auto i : vec1)
        cout << i << " ";
    cout << endl;
  
    cout << "vec2: ";
    for (auto i : vec2)
        cout << i << " ";
    cout << endl;
    return 0;
}

Output
vec1: 6 7 8 9 

vec2: 1 2 3 4 

Time Complexity: O(1)
Auxiliary Space: O(1)




Next Article

Similar Reads

Article Tags :
Practice Tags :
three90RightbarBannerImg