C++ Standard Library C++ STL Library

C++ set - swap() Function



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

Syntax

template<class Key, class Compare, class Alloc>
void swap(
    set<Key,Compare,Alloc>& lhs,
    set<Key,Compare,Alloc>& rhs 
);
template<class Key, class Compare, class Alloc>
void swap(
    set<Key,Compare,Alloc>& lhs,
    set<Key,Compare,Alloc>& rhs 
 );

Parameters

lhs First set.
rhs Second set.

Return Value

None.

Time Complexity

Constant i.e, Θ(1)

Example:

In the example below, the swap() function is used to exchange all elements of set MySet1 with all elements of set MySet2.

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

  set<int>::iterator it;

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

  swap(MySet1, MySet2);

  cout<<"\n\nAfter Swapping, The MySet1 contains:";
  for(it = MySet1.begin(); it != MySet1.end(); ++it)
    cout<<" "<<*it;
  cout<<"\nAfter Swapping, The MySet2 contains:";
  for(it = MySet2.begin(); it != MySet2.end(); ++it)
    cout<<" "<<*it;
    
  return 0;
}

The output of the above code will be:

Before Swapping, The MySet1 contains: 10 20 30 40 50
Before Swapping, The MySet2 contains: 5 55 555

After Swapping, The MySet1 contains: 5 55 555
After Swapping, The MySet2 contains: 10 20 30 40 50

❮ C++ <set> Library