Swap elements from two list - C++ STL

C++ examples for STL:list

Description

Swap elements from two list

Demo Code

#include <iostream> 
#include <list> 
#include <algorithm> // copy algorithm 
#include <iterator> // ostream_iterator 
using namespace std; 

template < typename T > void printList( const list< T > &listRef ); 

int main() { /*from ww  w.ja v  a  2s . c o  m*/
   const int SIZE = 4; 
   int array[ SIZE ] = { 2, 6, 4, 8 }; 
   list< int > values; // create list of ints 
   list< int > otherValues; // create list of ints 

   // insert items in values 
   values.push_front( 1 ); 
   values.push_front( 2 ); 
   otherValues.push_back( 4 ); 
   otherValues.push_back( 3 ); 


   // swap elements of values and otherValues 
   values.swap( otherValues ); 
   cout << "\nAfter swap:\n        values contains: "; 
   printList( values ); 
   cout << "\n      otherValues contains: "; 
   printList( otherValues ); 
   
}

template < typename T > void printList( const list< T > &listRef ) { 
   if ( listRef.empty() ) // list is empty 
       cout << "List is empty"; 
   else 
   { 
       ostream_iterator< T > output( cout, " " ); 
       copy( listRef.begin(), listRef.end(), output ); 
   }
}

Result


Related Tutorials