function template
<algorithm>

std::swap_ranges

template <class ForwardIterator1, class ForwardIterator2>  ForwardIterator2 swap_ranges (ForwardIterator1 first1, ForwardIterator1 last1,                                ForwardIterator2 first2);
Exchange values of two ranges
Exchanges the values of each of the elements in the range [first1,last1) with those of their respective elements in the range beginning at first2.

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

The behavior of this function template is equivalent to:
1
2
3
4
5
6
7
8
9
10
template<class ForwardIterator1, class ForwardIterator2>
  ForwardIterator2 swap_ranges (ForwardIterator1 first1, ForwardIterator1 last1,
                                ForwardIterator2 first2)
{
  while (first1!=last1) {
    swap (*first1, *first2);
    ++first1; ++first2;
  }
  return first2;
}

Parameters

first1, last1
Forward iterators to the initial and final positions in one of the sequences to be swapped. The range used is [first1,last1), which contains all the elements between first1 and last1, including the element pointed by first1 but not the element pointed by last1.
first2
Forward iterator to the initial position in the other sequence to be swapped. The range used includes the same number of elements as the range [first1,last1).
The two ranges shall not overlap.

The ranges shall not overlap.
swap shall be defined to exchange the types pointed by both iterator types symmetrically (in both orders).

Return value

An iterator to the last element swapped in the second sequence.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// swap_ranges example
#include <iostream>     // std::cout
#include <algorithm>    // std::swap_ranges
#include <vector>       // std::vector

int main () {
  std::vector<int> foo (5,10);        // foo: 10 10 10 10 10
  std::vector<int> bar (5,33);        // bar: 33 33 33 33 33

  std::swap_ranges(foo.begin()+1, foo.end()-1, bar.begin());

  // print out results of swap:
  std::cout << "foo contains:";
  for (std::vector<int>::iterator it=foo.begin(); it!=foo.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

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

  return 0;
}

Output:
foo contains: 10 33 33 33 10
bar contains: 10 10 10 33 33


Complexity

Linear in the distance between first and last: Performs a swap operation for each element in the range.

Data races

The objects in both ranges are modified.

Exceptions

Throws if either an element assignment or an operation on iterators throws.
Note that invalid arguments cause undefined behavior.

See also