C++ 對映庫 - swap() 函式



描述

C++ 函式std::map::swap()交換 map 的內容與 map x 的內容。

宣告

以下是來自 std::map 標頭檔案的 std::map::swap() 函式的宣告。

C++98

void swap (map& x);

引數

x - 另一個相同型別的 map 物件。

返回值

異常

此成員函式不丟擲異常。

時間複雜度

常數,即 O(1)

示例

以下示例演示了 std::map::swap() 函式的使用方法。

#include <iostream>
#include <map>

using namespace std;

int main(void) {
   map<char, int> m1 = {
      {'a', 1},
      {'b', 2},
      {'c', 3},
      {'d', 4},
      {'e', 5},
      };

   map<char, int> m2;

   m2.swap(m1);

   cout << "Map contains following elements" << endl;

   for (auto it = m2.begin(); it != m2.end(); ++it)
      cout << it->first << " = " << it->second << endl;

   return 0;
}

讓我們編譯並執行上述程式,這將產生以下結果:

Map contains following elements
a = 1
b = 2
c = 3
d = 4
e = 5
map.htm
廣告

© . All rights reserved.