public member function
<map>

std::map::swap

void swap (map& x);
交換內容
Exchanges the content of the container by the content of x, which is another map of the same type. Sizes may differ.

呼叫此成員函式後,此容器中的元素將是呼叫前 x 中的元素,而 x 中的元素將是呼叫前this容器中的元素。所有迭代器、引用和指標對於交換後的物件仍然有效。

Notice that a non-member function exists with the same name, swap, overloading that algorithm with an optimization that behaves like this member function.

Whether the internal container allocators and comparison objects are swapped is undefined.
Whether the internal container allocators are swapped is not defined, unless in the case the appropriate allocator trait indicates explicitly that they shall propagate.

The internal comparison objects are always exchanged, using swap.

引數

x
Another map container of the same type as this (i.e., with the same template parameters,, T, CompareAlloc)其內容與此容器的內容交換。

返回值



示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// swap maps
#include <iostream>
#include <map>

int main ()
{
  std::map<char,int> foo,bar;

  foo['x']=100;
  foo['y']=200;

  bar['a']=11;
  bar['b']=22;
  bar['c']=33;

  foo.swap(bar);

  std::cout << "foo contains:\n";
  for (std::map<char,int>::iterator it=foo.begin(); it!=foo.end(); ++it)
    std::cout << it->first << " => " << it->second << '\n';

  std::cout << "bar contains:\n";
  for (std::map<char,int>::iterator it=bar.begin(); it!=bar.end(); ++it)
    std::cout << it->first << " => " << it->second << '\n';

  return 0;
}

輸出
foo contains:
a => 11
b => 22
c => 33
bar contains:
x => 100
y => 200


複雜度

常量。

迭代器有效性

指向兩個容器中元素的的所有迭代器、指標和引用仍然有效,但現在指向另一個容器中的元素,並在其中迭代。
Note that the end iterators do not refer to elements and may be invalidated.

資料競爭

容器和 x 都被修改。
No contained elements are accessed by the call (although see iterator validity above).

異常安全

如果兩個容器中的分配器進行比較相等,或者它們的 分配器特性 表明分配器應該 傳播,則該函式永遠不會丟擲異常(無異常保證)。
否則,將導致未定義行為

另見