C++ STL | vector::swap() Function with Example

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 Sanjeev, on May 06, 2019

C++ STL vector::swap() function

vector::swap() function is used to swap/exchange the content of two vectors with the same type, their sizes may differ.

The contents of vector1 are exchanged with the content of vector2. Vectors must be of the same type i.e. either both of them are of type int, string, long, etc.

This is not necessary that both of the vectors must have the same size i.e. size of both the vectors may differ from each other.

Note: Both the containers/vectors are modified after the call of this function.

Syntax of vector::swap() function

    vector1.swap(vector2);

Parameter(s): vector2 – another vector with that we have to swap the content of first vector vector1.

Return value: void – it returns nothing.

Time Complexity: O(1) i.e constant order

Example:

    Input:
    vector<int> vector1{ 1, 2, 3, 4, 5 };
    vector<int> vector2{ 6, 7, 8, 9, 10 };

    Function call:
    vector1.swap(vector2);

    Output:
    Vector1: 1 2 3 4 5
    Vector2: 6 7 8 9 10 
    After swapping...
    Vector1: 6 7 8 9 10 
    Vector2: 1 2 3 4 5 

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

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

int main()
{

    vector<int> vector1{ 1, 2, 3, 4, 5 };
    vector<int> vector2{ 6, 7, 8, 9, 10 };

    // Before Swapping vector-1 and vector-2
    cout << "Vector 1" << endl;
    for (auto i : vector1)
        cout << i << " ";

    cout << "\n";

    cout << "Vector 2" << endl;
    for (auto i : vector2)
        cout << i << " ";
    cout << "\n";

    // Swapping vector-1 and vector-2
    vector1.swap(vector2);

    // After swapping vector-1 and vector-2
    cout << "Vector 1" << endl;
    for (auto i : vector1)
        cout << i << " ";

    cout << "\n";

    cout << "Vector 2" << endl;
    for (auto i : vector2)
        cout << i << " ";

    return 0;
}

Output

Vector 1 
1 2 3 4 5
Vector 2 
6 7 8 9 10 
Vector 1 
6 7 8 9 10 
Vector 2 
1 2 3 4 5 

Related Tutorials



Comments and Discussions!

Load comments ↻





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