Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ฟังก์ชัน unordered_multimap::swap() ใน C++ STL

ฟังก์ชัน unordered_multimap::swap() ใน C++ STL ใช้สลับสมาชิกของ Multimap หนึ่งไปยังอีกอันที่มีขนาดและชนิดเดียวกัน

อัลกอริทึม

Begin
    Declare two empty map containers m, m1
    Insert values into both m, m1
    Perform swap() to swap values
    Print swapped values of m
    Print swapped values of m1
End.

โค้ดตัวอย่าง

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

int main() {
    unordered_map<char, int> m, m1; // empty map containers
    m.insert(pair<char, int>('b', 10));
    m.insert(pair<char, int>('c', 30));
    m.insert(pair<char, int>('d', 40));
    m1.insert(pair<char, int>('a', 20));
    m1.insert(pair<char, int>('e', 70));
    m1.insert(pair<char, int>('f', 60));
    m.swap(m1); // swap values
    cout << "\nKey and values of 1st set are:";
    for (auto it = m.begin(); it != m.end(); it++)
        cout << "{" << it->first << ", " << it->second << "} ";
    cout << "\nKey and values of 2nd set are:";
    for (auto it = m1.begin(); it != m1.end(); it++)
        cout << "{" << it->first << ", " << it->second << "} ";
    return 0;
}

ผลลัพธ์

Key and values of 1st set are: {f, 60} {a, 20} {e, 70}
Key and values of 2nd set are: {d, 40} {b, 10} {c, 30}.