C++ Standard Library C++ STL Library

C++ <valarray> - swap() Function



The C++ valarray::swap function is used to exchange all elements of one valarray with all elements of another valarray. To apply this function, the data-type of both valarrays must be same, although the size may differ.

Syntax

void swap( valarray& other );
void swap( valarray& other ) noexcept;

Parameters

other Specify valarray, whose elements need to be exchanged with another valarray.

Return Value

None.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the valarray::swap function is used to exchange all elements of valarray va1 with all elements of valarray va2.

#include <iostream>
#include <valarray>
using namespace std;
 
int main (){
  valarray<int> va1{10, 20, 30, 40, 50};
  valarray<int> va2{5, 55, 555};

  cout<<"Before Swapping, The va1 contains:";
  for(int i = 0; i < va1.size(); i++)
    cout<<va1[i]<<" ";
  cout<<"\nBefore Swapping, The va2 contains:";
  for(int i = 0; i < va2.size(); i++)
    cout<<va2[i]<<" "; 

  va1.swap(va2);

  cout<<"\n\nAfter Swapping, The va1 contains:";
  for(int i = 0; i < va1.size(); i++)
    cout<<va1[i]<<" ";
  cout<<"\nAfter Swapping, The va2 contains:";
  for(int i = 0; i < va2.size(); i++)
    cout<<va2[i]<<" ";

  return 0;
}

The output of the above code will be:

Before Swapping, The va1 contains:10 20 30 40 50 
Before Swapping, The va2 contains:5 55 555 

After Swapping, The va1 contains:5 55 555 
After Swapping, The va2 contains:10 20 30 40 50 

❮ C++ <valarray> Library