function template
<unordered_map>

std::swap (unordered_map)

template <class Key, class T, class Hash, class Pred, class Alloc>  void swap ( unordered_map<Key,T,Hash,Pred,Alloc>& lhs,              unordered_map<Key,T,Hash,Pred,Alloc>& rhs );
Exchanges contents of two unordered_map containers
The contents of container lhs are exchanged with those of rhs. Both container objects must be of the same type (same template parameters), although sizes may differ.

After the call to this function, the elements in lhs are those which were in rhs before the call, and the elements of rhs are those which were in lhs. Other objects kept internally by the containers (such as their hasher or key_equal objects) are also swapped.

This is a specialization of the generic algorithm swap that improves its performance by exchanging internal pointers to data, without actually performing any copies or moves on the individual elements.

Parameters

lhs,rhs
unordered_map containers (to the left- and right-hand side of the operator, respectively), having both the same template parameters (Key, T, Hash, Pred and Alloc).

Return value

none

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// swap (unordered_map specialization)
#include <iostream>
#include <string>
#include <unordered_map>

int main ()
{
  std::unordered_map<std::string,std::string>
     first = {{"Star Wars","G. Lucas"},{"Alien","R. Scott"},{"Terminator","J. Cameron"}},
     second  = {{"Inception","C. Nolan"},{"Donnie Darko","R. Kelly"}};

  swap(first,second);

  std::cout << "first: ";
  for (auto& x: first) std::cout << x.first << " (" << x.second << "), ";
  std::cout << std::endl;

  std::cout << "second: ";
  for (auto& x: second) std::cout << x.first << " (" << x.second << "), ";
  std::cout << std::endl;

  return 0;
}

Possible output:
first: Inception (C. Nolan), Donnie Darko (R. Kelly),
second: Alien (R. Scott), Terminator (J. Cameron), Star Wars (G. Lucas),


Complexity

Constant.

Iterator validity

All iterators, pointers and references remain valid, but now are referring to elements in the other container, and iterate in it.

See also