C++ Standard Library C++ STL Library

C++ <vector> - swap() Function



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

Syntax

void swap (vector& other);
void swap (vector& other);

Parameters

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

Return Value

None.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the vector::swap function is used to exchange all elements of vector MyVec1 with all elements of vector MyVec2.

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

  vector<int>::iterator it;

  cout<<"Before Swapping, The MyVec1 contains:";
  for(it = MyVec1.begin(); it != MyVec1.end(); ++it)
    cout<<" "<<*it;
  cout<<"\nBefore Swapping, The MyVec2 contains:";
  for(it = MyVec2.begin(); it != MyVec2.end(); ++it)
    cout<<" "<<*it;

  MyVec1.swap(MyVec2);

  cout<<"\n\nAfter Swapping, The MyVec1 contains:";
  for(it = MyVec1.begin(); it != MyVec1.end(); ++it)
    cout<<" "<<*it;
  cout<<"\nAfter Swapping, The MyVec2 contains:";
  for(it = MyVec2.begin(); it != MyVec2.end(); ++it)
    cout<<" "<<*it;

  return 0;
}

The output of the above code will be:

Before Swapping, The MyVec1 contains: 10 20 30 40 50
Before Swapping, The MyVec2 contains: 5 55 555

After Swapping, The MyVec1 contains: 5 55 555
After Swapping, The MyVec2 contains: 10 20 30 40 50

❮ C++ <vector> Library