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

template <class T, class Alloc>
void swap (vector<T,Alloc>& lhs, 
           vector<T,Alloc>& rhs);
template <class T, class Alloc>
void swap (vector<T,Alloc>& lhs, 
           vector<T,Alloc>& rhs);

Parameters

lhs First vector.
rhs Second vector.

Return Value

None.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, 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;

  swap(MyVec1, 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