Swaps elements of two ranges

You're viewing an older version of this page (#4133). View the current version.

View versions (1)

Definition

The swap_ranges() algorithm is defined in the standard header <algorithm> and in the nonstandard backward-compatibility header <algo.h>.

Interface

#include <algorithm>
template < class ForwardIterator1, class ForwardIterator2 >
   ForwardIterator2 swap_ranges(
      ForwardIterator1 first1, 
      ForwardIterator1 last1,
      ForwardIterator2 first2
   );

Parameters:

ParameterDescription
first1A forward iterator pointing to the first position of the first range whose elements are to be exchanged
last1A forward iterator pointing to one past the final position of the first range whose elements are to be exchanged
first2A forward iterator pointing to the first position of the second range whose elements are to be exchanged

Description

Swap_ranges swaps the elements of two sequence, that is each element at a position in the first sequence is replaced by the element at the same position in the second sequence and vice-versa.

Return Value

Returns an iterator pointing to the end of the second range.

Complexity

The complexity is linear. There are performed last1 - first1 swaps.

References

Example 1
Problem

This program illustrates the functionality of swap_ranges algorithm.

Workings
#include <vector>
#include <deque>
#include <algorithm>
#include <iostream>

using namespace std;
 
int main()
{
  vector <int> vec1;
  deque <int> deq1;
  vector <int>::iterator vec1Iter1;
  deque<int>::iterator deq1Iter;
  int i,j;
  for (i = 10; i <= 15; i++)
    vec1.push_back(i);
  for (j =24; j <= 29; j++)
    deq1.push_back(j);

  cout <<"Vector vec1 data:\n";
  for (vec1Iter1 = vec1.begin(); vec1Iter1 != vec1.end(); vec1Iter1++)
    cout <<*vec1Iter1<<" ";
  cout <<endl;

  cout <<"\nDeque deq1 data:\n";
  for (deq1Iter = deq1.begin(); deq1Iter != deq1.end(); deq1Iter++)
    cout <<*deq1Iter<<" ";
  cout <<endl;

  swap_ranges(vec1.begin(), vec1.end(), deq1.begin());
  cout <<"\nAfter the swap_range(), vector vec1 data:\n";
  for (vec1Iter1 = vec1.begin(); vec1Iter1 != vec1.end(); vec1Iter1++)
    cout <<*vec1Iter1<<" ";
  cout <<endl;

  cout <<"\nAfter the swap_range() deque deq1 data:\n";
  for (deq1Iter = deq1.begin(); deq1Iter != deq1.end(); deq1Iter++)
    cout <<*deq1Iter<<" ";
  cout <<endl;

  return 0;
}
Solution

Output:

Vector vec1 data:
10 11 12 13 14 15

Deque deq1 data:
24 25 26 27 28 29

After the swap_range(), vector vec1 data:
24 25 26 27 28 29

After the swap_range() deque deq1 data:
10 11 12 13 14 15

See Also