copy


Copy a range of items to another area.

Copy the elements from the range [ first , last ) into a range of the same size starting at result, using operator= to replace the existing elements. Return an iterator of the same type as result positioned immediately after the last new element.

Library

Standards<ToolKit>

Declaration


#include <algorithm>

template< class InputIterator, class OutputIterator >
OutputIterator copy
  (
  InputIterator first,
  InputIterator last,
  OutputIterator result
  );
  

Complexity

Time complexity is linear, as ( last - first ) assignments are performed. Space complexity is constant.

Example <ospace/osstd/examples/copy1.cpp>
#include <iostream>
#include <string.h>
#include <algorithm>

char string[ 23 ] = "A string to be copied.";

void
main()
  {
  char result[ 23 ];
  copy( string, string + 23, result );
  cout << " Src: " << string << "\nDest: " << result << "\n";
  }
 Src: A string to be copied.

Dest: A string to be copied.
Example <ospace/osstd/examples/copy2.cpp>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>

void
main()
  {
  vector< int > v( 10 );
  for ( size_t i = 0; i < v.size(); ++i )
    v[ i ] = i;
  ostream_iterator< int > iter( cout, " " );

  copy( v.begin(), v.end(), iter );

  cout << "\n";
  }

0 1 2 3 4 5 6 7 8 9
Example <ospace/osstd/examples/copy3.cpp>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>

void
main()
  {
  vector<int> v1( 10 );
  for ( size_t i = 0; i < v1.size(); ++i )
    v1[ i ] = i;
  vector< int > v2( 10 );

  copy( v1.begin(), v1.end(), v2.begin() );

  ostream_iterator< int > iter( cout, " " );
  copy( v2.begin(), v2.end(), iter );
  cout << "\n";
  }

0 1 2 3 4 5 6 7 8 9
Example <ospace/osstd/examples/copy4.cpp>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>

void
main()
  {
  vector< int > v1( 10 );
  for ( size_t loc = 0; loc < v1.size(); ++loc )
    v1[ loc ] = loc;
  vector< int > v2;
  insert_iterator< int_vector > i( v2, v2.begin() );

  copy( v1.begin(), v1.end(), i );
  ostream_iterator< int > outIter( cout, " " );

  copy( v2.begin(), v2.end(), outIter );
  cout << "\n";
  }


0 1 2 3 4 5 6 7 8 9

Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.