vector::swap() function with example in C++ STL

C++ STL vector::swap() function: Here, we are going to learn about the swap() function of vector header in C++ STL with example.
Submitted by IncludeHelp, on May 16, 2019

C++ vector::swap() function

vector::swap() is a library function of "vector" header, it is used to swap the content of the vectors, it is called with a vector and accepts another vector as an argument and swaps their content. (Sizes of both of the vectors may differ).

Note: To use vector, include <vector> header.

Syntax of vector::swap() function

    vector::swap(vector& v);

Parameter(s): v – It is another vector to be swapped content with current vector.

Return value: void – It returns nothing.

Example:

    Input:
    vector<int> v1{ 10, 20, 30, 40, 50 };
    vector<int> v2{ 100, 200, 300 };
    
    //swapping content of the vectors
    v1.swap(v2);

    Output:
    //if we print the values
    v1: 100 200 300
    v2: 10 20 30 40 50

C++ program to demonstrate example of vector::swap() function

//C++ STL program to demonstrate example of
//vector::erase() function

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    //vector declaration
    vector<int> v1{ 10, 20, 30, 40, 50 };
    vector<int> v2{ 100, 200, 300 };

    //printing the sizes and values of the vectors
    cout << "before swap() call..." << endl;
    cout << "size of v1: " << v1.size() << endl;
    cout << "size of v2: " << v2.size() << endl;

    cout << "v1: ";
    for (int x : v1)
        cout << x << " ";
    cout << endl;

    cout << "v2: ";
    for (int x : v2)
        cout << x << " ";
    cout << endl;

    //swapping the content of the vectors
    v1.swap(v2);

    //printing the sizes and values of the vectors
    cout << "after swap() call..." << endl;
    cout << "size of v1: " << v1.size() << endl;
    cout << "size of v2: " << v2.size() << endl;

    cout << "v1: ";
    for (int x : v1)
        cout << x << " ";
    cout << endl;

    cout << "v2: ";
    for (int x : v2)
        cout << x << " ";
    cout << endl;

    return 0;
}

Output

before swap() call...
size of v1: 5
size of v2: 3
v1: 10 20 30 40 50
v2: 100 200 300
after swap() call...
size of v1: 3
size of v2: 5
v1: 100 200 300
v2: 10 20 30 40 50

Reference: C++ vector::swap()


Related Tutorials



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.