Skip to content
Related Articles

Related Articles

How to quickly swap two arrays of same size in C++?
  • Difficulty Level : Basic
  • Last Updated : 28 May, 2017
GeeksforGeeks - Summer Carnival Banner

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.




// Illustrating the use of swap function
// to swap two arrays
#include <iostream>
#include <utility>
using namespace std;
  
// Driver Program
int main ()
{
    int a[] = {1, 2, 3, 4};
    int b[] = {5, 6, 7, 8};
    int n = sizeof(a)/sizeof(a[0]);
  
    swap(a, b);
  
    cout << "a[] = ";
    for (int i=0; i<n; i++)
        cout << a[i] << ", ";
  
    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,

This article is contributed by Shambhavi Singh. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :