function template
<map>

std::swap (map)

template <class Key, class T, class Compare, class Alloc>  void swap (map<Key,T,Compare,Alloc>& x, map<Key,T,Compare,Alloc>& y);
交換兩個map的內容
容器x的內容與y的內容交換。兩個容器物件必須是相同的型別(相同的模板引數),但大小可以不同。

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

這是通用演算法 swap 的一個過載,它透過相互轉移資產的所有權到另一個容器來提高效能(即,容器交換資料的引用,而不實際執行任何元素複製或移動):其行為如同x.swap(y)被呼叫。

引數

x,y
相同型別的 map 容器(即,具有相同的模板引數, T, 比較Alloc).

返回值



示例

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;

  swap(foo,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


複雜度

常量。

迭代器有效性

指向兩個容器中元素的 所有迭代器、指標和引用 保持有效,並且現在指向呼叫前它們所指向的相同元素,但在另一個容器中,它們現在進行迭代。
請注意,end iterators 不指向任何元素,並且可能失效。

資料競爭

xy 這兩個容器都被修改。
呼叫時不會訪問任何包含的元素(儘管請參閱上面的iterator validity)。

異常安全

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

另見