function template

std::swap_ranges

<algorithm>
template < class ForwardIterator1, class ForwardIterator2 >
  ForwardIterator2 swap_ranges ( ForwardIterator1 first1, ForwardIterator1 last1,
                                 ForwardIterator2 first2 );
Exchange values of two ranges
Swaps 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 behavior of this function template is equivalent to:
1
2
3
4
5
6
7
template<class ForwardIterator1, class ForwardIterator2>
  ForwardIterator2 swap_ranges ( ForwardIterator1 first1, ForwardIterator1 last1,
                                 ForwardIterator2 first2 )
{
  while (first1!=last1) swap(*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.


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
25
26
// swap_ranges example
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main () {
  vector<int> first (5,10);        //  first: 10 10 10 10 10
  vector<int> second (5,33);       // second: 33 33 33 33 33
  vector<int>::iterator it;

  swap_ranges(first.begin()+1, first.end()-1, second.begin());

  // print out results of swap:
  cout << " first contains:";
  for (it=first.begin(); it!=first.end(); ++it)
    cout << " " << *it;

  cout << "\nsecond contains:";
  for (it=second.begin(); it!=second.end(); ++it)
    cout << " " << *it;

  cout << endl;

  return 0;
}


Output:
 first contains: 10 33 33 33 10
second contains: 10 10 10 33 33

Complexity

Linear: Performs as many swaps as elements are in the range [first1,last1).

See also