Open In App

How to quickly swap two arrays of same size in C++?

Last Updated : 02 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two arrays a[] and b[] of same size, we need to swap their contents. Example :

Input:
a[] = {1, 2, 3, 4}
b[] = {5, 6, 7, 8}

Output:
a[] = {5, 6, 7, 8}
b[] = {1, 2, 3, 4}

A simple solution is to iterate over elements of both arrays and swap them one by one.

A quick solution is to use std::swap(). It can directly swap arrays if they are of same size.

C++
// C++ program to use swap function to swap two arrays

// Include necessary header files
#include <algorithm>
#include <iostream>

using namespace std;

int main()
{
    // Initialize two arrays a and b
    int a[] = { 1, 2, 3, 4 };
    int b[] = { 5, 6, 7, 8 };

    // Calculate the size of the arrays
    int n = sizeof(a) / sizeof(a[0]);

    // Swap the contents of arrays a and b
    swap(a, b);

    // Print the contents of array a after swapping
    cout << "a[] = ";
    for (int i = 0; i < n; i++)
        cout << a[i] << ", ";

    // Print the contents of array b after swapping
    cout << "\nb[] = ";
    for (int i = 0; i < n; i++)
        cout << b[i] << ", ";

    return 0;
}

Output
a[] = 5, 6, 7, 8, 
b[] = 1, 2, 3, 4, 

Next Article
Article Tags :
Practice Tags :

Similar Reads