×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

unordered_map swap() Function in C++ with Examples

C++ unordered_map swap() Function: Here, we will learn about the swap() function, its usages, syntax and examples.
Submitted by Shivang Yadav, on July 20, 2022

An unordered_map is a special type of container that stores data in the form of key-value pairs in an unordered manner. The key stored is used to identify the data value mapped to it uniquely.

C++ STL std::unordered_map::swap() Function

The swap() function is used to swap the elements of two maps with one another. This will swap the elements of unordered_map map1 with the elements of unordered_map map2 and vise vera.

Note: For swapping unordered_maps they must be of the same type.

Syntax

unordered_mapMap1.swap(unordered_mapMap2);

Parameter(s)

It accepts a single parameter. It is the order map whose elements are needed to be swapped.

Return value

It does not return any value.

Sample Input and Output

Input: 
map1 = {{1, 'a'}, {6, 'h'}}
map2 = {{12, 'x'}, {5, 'n'}}

Output:
map1 = {{12, 'x'}, {5, 'n'}}
map2 = {{1, 'a'}, {6, 'h'}}

Example

#include <iostream>
#include <unordered_map>
using namespace std;

int main()
{
    unordered_map<int, char> myMap1 = { { 1, 'a' }, { 5, 'x' }, { 9, 's' } };
    unordered_map<int, char> myMap2 = { { 6, 'e' }, { 15, 'k' }, { 10, 'n' } };

    cout << "map1 : ";
    for (auto x : myMap1)
        cout << x.first << " : " << x.second << "\t";
    cout << endl;

    cout << "map2 : ";
    for (auto x : myMap2)
        cout << x.first << " : " << x.second << "\t";
    cout << endl;

    cout << "After swapping maps\n";
    myMap1.swap(myMap2);
    cout << "map1 : ";
    for (auto x : myMap1)
        cout << x.first << " : " << x.second << "\t";
    cout << endl;

    cout << "map2 : ";
    for (auto x : myMap2)
        cout << x.first << " : " << x.second << "\t";
    cout << endl;

    return 0;
}

Output

map1 : 9 : s    5 : x   1 : a
map2 : 10 : n   15 : k  6 : e
After swapping maps
map1 : 10 : n   15 : k  6 : e
map2 : 9 : s    5 : x   1 : a

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.