C++ Standard Library C++ STL Library

C++ <array> - swap() Function



The C++ <array> swap() function is used to exchange all elements of one array with all elements of another array. To apply this function, the data-type and size of both arrays must be same.

Syntax

template<class T, size_t N>
void swap(stack<T,N>& lhs,
          stack<T,N>& rhs);

Parameters

lhs First array.
rhs Second array.

Return Value

None.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the swap() function is used to exchange all elements of array arr1 with all elements of array arr2.

#include <iostream>
#include <array>
using namespace std;
 
int main (){
  array<int, 5> arr1{10, 20, 30, 40, 50};
  array<int, 5> arr2{1, 2, 3, 4, 5};

  array<int, 5>::iterator it;

  cout<<"Before Swapping, The arr1 contains:";
  for(it = arr1.begin(); it != arr1.end(); ++it)
    cout<<" "<<*it;
  cout<<"\nBefore Swapping, The arr2 contains:";
  for(it = arr2.begin(); it != arr2.end(); ++it)
    cout<<" "<<*it;

  swap(arr1, arr2);

  cout<<"\n\nAfter Swapping, The arr1 contains:";
  for(it = arr1.begin(); it != arr1.end(); ++it)
    cout<<" "<<*it;
  cout<<"\nAfter Swapping, The arr2 contains:";
  for(it = arr2.begin(); it != arr2.end(); ++it)
    cout<<" "<<*it;

  return 0;
}

The output of the above code will be:

Before Swapping, The arr1 contains: 10 20 30 40 50
Before Swapping, The arr2 contains: 1 2 3 4 5

After Swapping, The arr1 contains: 1 2 3 4 5
After Swapping, The arr2 contains: 10 20 30 40 50

❮ C++ <array> Library

5