C++ multiset swap() function

In this tutorial, we will learn about the swap() function used in the multiset container of C++. We will also see a sample code to understand multiset swap() function.

multiset in C++

The C++ multiset is an associative container. An associative container is one which can directly access elements using keys.

The elements need not be in sequential order. The advantage of a multiset is that it allows the storage of duplicate keys.

Create multiset in C++

The following syntax needs to be followed to create a multiset:

multiset<int> intMultiset; // creates a multiset of ints

To create and access a multiset object, we need to include the header file <set>.

The multiset container is bidirectional, i.e., traversal is possible in both forward and backward directions.

C++ multiset swap() function:

The C++ multiset container supports many inbuilt functions, one of which is the swap() function.

As the name suggests, this function allows for swapping or exchange of two values.

Both the multisets must be of the same size for the swap() function to be accessible.

Syntax of swap() function:

The syntax is given below:

void swap(multiset& c)

‘c’ is the multiset container to exchange the contents with.

Sample code to demonstrate the usage of swap() function in multiset:

Let us see an example to understand how the swapping of two multisets takes place:

#include<iostream>
#include<set>
#include<iterator>
using namespace std;
int main()
{
    multiset<int> m1;
    m1.insert(1);
    m1.insert(2);
    m1.insert(3);
    multiset<int> m2;
    m2.insert(4);
    m2.insert(5);
    m2.insert(6);
    swap(m1,m2);
    multiset<int>::iterator itr;
    cout<<"after swapping\n";
    cout<<"contents of m1:"<<endl;
    for(itr=m1.begin();itr!=m1.end();itr++)
    {
        cout<<*itr<<" ";
    }
    cout<<"\n";
    cout<<"contents of m2:"<<endl;
    for(itr=m2.begin();itr!=m2.end();itr++)
    {
        cout<<*itr<<" ";
    }
    return 0;

}

The above code gives the output:

after swapping
contents of m1:
4 5 6
contents of m2:
1 2 3
Process returned 0 (0x0)   execution time : 0.070 s
Press any key to continue.

With this, we come to the end of this tutorial.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *