Windows Dev Center

Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

swap

Exchanges the values of the elements between two types of objects, assigning the contents of the first object to the second object and the contents of the second to the first.

template<class Type> 
   void swap( 
      Type& _Left,  
      Type& _Right 
   );

_Left

The first object to have its elements exchanged.

_Right

The second object to have its elements exchanged.

This algorithm is exceptional in the STL in being designed to operate on individual elements rather than on a range of elements.

// alg_swap.cpp
// compile with: /EHsc
#include <vector>
#include <algorithm>
#include <iostream>

bool greater5 ( int value )
{
   return value >5;
}

int main( ) 
{
   using namespace std;
   vector <int> v1, v2;
   vector <int>::iterator Iter1, Iter2, result;

   int i;
   for ( i = 0 ; i <= 10 ; i++ )
   {
      v1.push_back( i );
   }

   int ii;
   for ( ii = 0 ; ii <= 4 ; ii++ )
   {
      v2.push_back( 5 );
   }

   cout << "Vector v1 is ( " ;
   for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
      cout << *Iter1 << " ";
   cout << ")." << endl;

   cout << "Vector v2 is ( " ;
   for ( Iter2 = v2.begin( ) ; Iter2 != v2.end( ) ; Iter2++ )
      cout << *Iter2 << " ";
   cout << ")." << endl;

   swap( v1, v2 );

   cout << "Vector v1 is ( " ;
   for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
      cout << *Iter1 << " ";
   cout << ")." << endl;

   cout << "Vector v2 is ( " ;
   for ( Iter2 = v2.begin( ) ; Iter2 != v2.end( ) ; Iter2++ )
      cout << *Iter2 << " ";
   cout << ")." << endl;
}
Vector v1 is ( 0 1 2 3 4 5 6 7 8 9 10 ). Vector v2 is ( 5 5 5 5 5 ). Vector v1 is ( 5 5 5 5 5 ). Vector v2 is ( 0 1 2 3 4 5 6 7 8 9 10 ).

Header: <algorithm>

Namespace: std

Community Additions

Show:
© 2015 Microsoft