Copies a range starting with the first element

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

View versions (1)

Definition

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

Interface

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

Parameters:

ParameterDescription
firstAn input iterator addressing the position of the first element in the source range
lastAn input iterator addressing the position that is one past the final element in the source range
resultAn output iterator addressing the position of the first element in the destination range

Description

Copy copies a sequence to another location, this new sequence will start at result.

Return Value

Returns an iterator on the element following the last copied element.

Complexity

The complexity is linear, there are last - first assignments.

References

Example 1
Problem

This program illustrates the use of the STL copy() algorithm to copy integers from a vector to the standard output, using an output stream iterator.

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

using namespace std;

int main()
{
  int a[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
  vector<int> v(a, a+10);
  cout <<"\nHere are the contents of v, displayed in the "\"usual\" way:\n";
  for (vector<int>::size_type i=0; i<v.size(); i++)
    cout <<v.at(i)<<" ";

  cout <<"\nAnd here they are again, displayed this time using "
         "\nthe copy algorithm and an output stream iterator:\n";
  copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));

  return 0;
}
Solution

Output:

Here are the contents of v, displayed in the "usual" way:
10 20 30 40 50 60 70 80 90 100

And here they are again, displayed this time using
the copy algorithm and an output stream iterator:
10 20 30 40 50 60 70 80 90 100

See Also