function template
<algorithm>

std::iter_swap

template <class ForwardIterator1, class ForwardIterator2>
  void iter_swap (ForwardIterator1 a, ForwardIterator2 b);
Exchange values of objects pointed to by two iterators
Swaps the elements pointed to by a and b.

The function calls swap (unqualified) to exchange the elements.

The behavior of this function template is equivalent to:
1
2
3
4
5
template <class ForwardIterator1, class ForwardIterator2>
  void iter_swap (ForwardIterator1 a, ForwardIterator2 b)
{
  swap (*a, *b);
}


Parameters

a, b
Forward iterators to the objects to swap.
swap shall be defined to exchange values of the type pointed to by the iterators.

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
// iter_swap example
#include <iostream>     // std::cout
#include <algorithm>    // std::iter_swap
#include <vector>       // std::vector

int main () {

  int myints[]={10,20,30,40,50 };              //   myints:  10  20  30  40  50
  std::vector<int> myvector (4,99);            // myvector:  99  99  99  99

  std::iter_swap(myints,myvector.begin());     //   myints: [99] 20  30  40  50
                                               // myvector: [10] 99  99  99

  std::iter_swap(myints+3,myvector.begin()+2); //   myints:  99  20  30 [99] 50
                                               // myvector:  10  99 [40] 99

  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}


Output:
myvector contains: 10 99 40 99

Complexity

Constant: Calls swap once.

Data races

The objects pointed to by both iterators are modified.

Exceptions

Throws if the call to swap throws.
Note that invalid arguments cause undefined behavior.

See also