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


In this tutorial, we will be discussing a program to understand how to quickly swap two arrays of same size in C++.

For this we will be using a quick method called std::swap() for swapping the elements of the two given arrays.

Example

 Live Demo

#include <iostream>
#include <utility>
using namespace std;
   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,

Updated on: 02-Mar-2020

160 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements