C++ Unordered_set::swap() function



The C++ std::unordered_set::swap() function is used to exchange the contents of the unordered_set with others. If both the unordered_sets have the same contents, it does nothing; otherwise, exchange the contents of the unordered_sets with another unordered_set. The return type of this function is void which implies that it does not return any value.

Syntax

Following is the syntax of std::unordered_set::swap() function −

void swap ( unordered_set& other);

Parameters

  • other − It is another container to exchange the contents with.

Return Value

This function does not return any value.

Example 1

Let's look at the following example, where we are going to exchange the contents of the num_set1 with the contents of the num_set2.

#include
#include
#include
using namespace std;

int main () {
   //create unordered_sets
   unordered_set num_set1 = {1, 2, 3, 4, 5};
   unordered_set num_set2 = {6, 7, 8, 9, 10};
   cout<<"Contents of the num_set1 before swap operation: "<

Output

If we run the above code it will generate the following output −

Contents of the num_set1 before swap operation: 
5
4
3
2
1
Contents of the num_set2 before swap operation: 
10
9
8
7
6
Contents of the num_set1 after swap operation: 
10
9
8
7
6
Contents of the num_set2 after swap operation: 
5
4
3
2
1

Example 2

Consider the another scenario, where we are going to consider the unordered_sets of char type and applying the swap() function.

#include
#include
#include
using namespace std;

int main () {
   //create unordered_sets
   unordered_set char_set1 = {};
   unordered_set char_set2 = {'a', 'b', 'c', 'd'};
   cout<<"Size of the char_set1 before swap operation: "<

Output

Following is the output of the above code −

Size of the char_set1 before swap operation: 0
Contents of the char_set2 before swap operation: 
d
c
b
a
Contents of the char_set1 after swap operation: 
d
c
b
a
Size of the char_set2 after the swap operation: 0

Example 3

In the following example, we are going to consider the unordered_set of string type and applying the swap() function to exchange the contents of the unordered_set.

#include
#include
#include
using namespace std;

int main () {
   //create unordered_sets
   unordered_set str_set1 = {"Red", "Blue", "Yellow", "White"};
   unordered_set str_set2 = {"Apple", "Banana", "Mango", "Orange"};
   cout<<"Contents of the str_set1 before swap operation: "<

Output

Output of the above code is as follows −

Contents of the str_set1 before swap operation: 
White
Yellow
Blue
Red
Content of the str_set2 before swap operation: 
Mango
Banana
Orange
Apple
Contents of the str_set1 after swap operation: 
Mango
Banana
Orange
Apple
Content of the str_set2 after swap operation: 
White
Yellow
Blue
Red
Advertisements