vector swap() in C++

swap(): It is a build-in function in STL. It swaps data with another vector.

File: stl_vector.h

Parameter:

x – A vector of the same element and allocator types. This exchanges the elements 

between two vectors in constant time. 

Syntax:

vec.swap(x)

For Example:

vec ={1,2,3,4}

x  = {5,4,3,2,1}

vec.swap(x) =>

vec = {5,4,3,2,1}

x = {1,2,3,4}

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int main()
{
    vector<intvec1 = {1234};

    vector<intvec2 = {54321};

    vec1.swap(vec2);

    for (int i = 0i < vec1.size(); i++)
        cout << vec1[i] << " ";

    cout << "\n";
    for (int i = 0i < vec2.size(); i++)
        cout << vec2[i] << " ";
    
    return 0;
}


No comments:

Post a Comment