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).

异常安全

如果两个容器中的分配器进行比较相等,或者它们的 分配器特性 表明分配器应该 传播,则该函数永远不会抛出异常(无异常保证)。
否则,将导致未定义行为

另见