function template
<algorithm>

std::copy

template <class InputIterator, class OutputIterator>  OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result);
複製元素範圍
將範圍 [first,last) 中的元素複製到以 result 開頭的範圍。

該函式返回一個指向目標範圍結束處的迭代器(該迭代器指向最後一個被複制元素的下一個元素)。

範圍不能重疊,以至於 result 指向範圍 [first,last) 中的某個元素。 對於這種情況,請參見 copy_backward

此函式模板的行為等同於
1
2
3
4
5
6
7
8
9
template<class InputIterator, class OutputIterator>
  OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result)
{
  while (first!=last) {
    *result = *first;
    ++result; ++first;
  }
  return result;
}

引數

first, last
輸入迭代器,指向要複製的序列的起始和結束位置。範圍為 [first,last),其中包含 firstlast 之間的所有元素,包括 first 指向的元素,但不包括 last 指向的元素。
result
輸出迭代器,指向目標序列的起始位置。
此迭代器不應指向範圍 [first,last) 中的任何元素。

返回值

一個指向已複製元素的目標範圍結束處的迭代器。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// copy algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::copy
#include <vector>       // std::vector

int main () {
  int myints[]={10,20,30,40,50,60,70};
  std::vector<int> myvector (7);

  std::copy ( myints, myints+7, myvector.begin() );

  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it = myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;

  std::cout << '\n';

  return 0;
}

輸出
myvector contains: 10 20 30 40 50 60 70


複雜度

線性時間複雜度,複雜度與 firstlast 之間的 距離 成正比:對範圍中的每個元素執行一次賦值操作。

資料競爭

範圍 [first,last) 中的物件將被訪問(每個物件恰好訪問一次)。
result 和返回的迭代器之間的範圍內的物件將被修改(每個物件恰好被修改一次)。

異常

如果元素賦值或迭代器操作丟擲異常,則會丟擲異常。
請注意,無效引數會導致未定義行為

另見