C++ multimap::swap() Function



The C++ std::multimap::swap() function is used to exchange the contents of two multimaps. It swaps the elements, size, and allocator of the two multimaps without reallocating memory or altering individuals elements.

The swap() function can be called in two ways: as a member function or as a non-member function. The time complexity of the swap() when used as member function is Constant i.e.O(1) orelse it is linear i.e.O(n) when used as non-member function. you can find the syntaxes of both the ways below.

Syntax

Following is the syntax for std::multimap::swap() function.

void swap (multimap& x);
or	
void swap (multimap<Key,T,Compare,Alloc>& first, multimap<Key,T,Compare,Alloc>& second);

Parameters

  • x − It indicates the multimap object of same type.
  • first − It indicates the first multimap object
  • second − It indicates the second multimap object of same type.

Return value

This function does not return anything.

Example

Let's look at the following example, where we are going to demonstrate the usage of swap() function.

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a;
    std::multimap<int, std::string> b;
    a.insert({1, "Vanakam"});
    a.insert({2, "Namaste"});
    b.insert({3, "Hi"});
    b.insert({4, "Hello"});
    a.swap(b);
    std::cout << "First multimap contents after swap:" << std::endl;
    for (const auto& elem : a) {
        std::cout << elem.first << ": " << elem.second << std::endl;
    }
    std::cout << "second multimap contents after swap:" << std::endl;
    for (const auto& elem : b) {
        std::cout << elem.first << ": " << elem.second << std::endl;
    }
    return 0;
}

Output

Following is the output of the above code −

First multimap contents after swap:
3: Hi
4: Hello
second multimap contents after swap:
1: Vanakam
2: Namaste

Example

Consider the following scenario, where we are going to swap the two empty multimaps.

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a;
    std::multimap<int, std::string> b;
    a.swap(b);
    std::cout << "Size of first multimap after swap: " << a.size() << std::endl;
    std::cout << "SSize of second multimap after swap: " << b.size() << std::endl;
    return 0;
}

Output

Output of the above code is as follows −

Size of first multimap after swap: 0
Size of second multimap after swap: 0
multimap.htm
Advertisements