valarray swap() function in c++

The swap() function is defined in valarray header file. This function is used to swap the content of one valarray with another valarray.

Syntax:

void swap( valarray& valarray2 );

Parameter: This method accepts a parameter valarray2 which represents the another valarray with which we have to swap the old one.

Returns: This function doesn’t returns anything.

Below programs illustrate the above function:

Example 1:-

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to demonstrate
// example of swap() function.
  
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    // Initializing 1st valarray
    valarray<int> varr1 = { 12, 24, 36, 48 };
  
    // Initializing 2nd valarray
    valarray<int> varr2 = { 20, 40, 60, 80 };
  
    varr1.swap(varr2);
  
    // Displaying valarrays after swapping
    cout << "The contents of 1st valarray "
            "after swapping are : ";
  
    for (int& x : varr1)
        cout << x << " ";
  
    cout << endl;
  
    cout << "The contents of 2nd valarray "
            "after swapping are : ";
  
    for (int& x : varr2)
        cout << x << " ";
  
    cout << endl;
  
    return 0;
}

chevron_right


Output:

The contents of 1st valarray after swapping are : 20 40 60 80 
The contents of 2nd valarray after swapping are : 12 24 36 48

Example 2:-

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to demonstrate
// example of swap() function.
  
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    // Initializing 1st valarray
    valarray<int> varr1 = { -12, -24, -36, -48 };
  
    // Initializing 2nd valarray
    valarray<int> varr2 = { 20, 40, 60, 80 };
  
    varr1.swap(varr2);
  
    // Displaying valarrays after swapping
    cout << "The contents of 1st valarray "
            "after swapping are : ";
  
    for (int& x : varr1)
        cout << x << " ";
  
    cout << endl;
  
    cout << "The contents of 2nd valarray "
            "after swapping are : ";
  
    for (int& x : varr2)
        cout << x << " ";
  
    cout << endl;
  
    return 0;
}

chevron_right


Output:

The contents of 1st valarray after swapping are : 20 40 60 80 
The contents of 2nd valarray after swapping are : -12 -24 -36 -48


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.