unordered_multimap swap() 函式在 C++ STL 中


C++ STL 中的 unordered_multimap swap() 函式用於將一個多重對映中的元素交換到另一個大小和型別相同的元素。

演算法

Begin
   Declaring two empty map container m, m1.
   Insert some values in both m, m1 map containers.
   Perform swap() function to swap the values of m, m1 map containers.
   Printing the swapped values of m map container.
   Printing the swapped values of m1 map container.
End.

示例程式碼

 線上演示

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

int main() {
   unordered_map<char, int> m,m1; // declaring m, m1 as empty map container

   m.insert (pair<char, int>('b', 10)); //inserting values in map container
   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); // swapping the values of two map container.

   cout << "\n Key and values of 1st set are:";
   for (auto it = m.begin(); it != m.end(); it++) {
      cout << "{" << it->first << ", " << it->second << "} "; // printing the swapped values of m map container
   }

   cout << "\n Key and values of 2nd set are:"; // printing the swapped values of m1 map container
   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}.

更新時間:2019 年 7 月 30 日

106 次瀏覽

開啟您的職業道路

透過完成課程獲得認證

入門
廣告
© . All rights reserved.