function template
<algorithm>

std::copy_n

template <class InputIterator, class Size, class OutputIterator>  OutputIterator copy_n (InputIterator first, Size n, OutputIterator result);
Copy elements
Copies the first n elements from the range beginning at first into the range beginning at result.

The function returns an iterator to the end of the destination range (which points to one past the last element copied).

If n is negative, the function does nothing.

If the ranges overlap, some of the elements in the range pointed by result may have undefined but valid values.

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

引數

first
Input iterators to the initial position in a sequence of at least n elements to be copied.
InputIterator shall point to a type assignable to the elements pointed by OutputIterator.
n
Number of elements to copy.
If this value is negative, the function does nothing.
Size 必須是(可轉換為)整數型別。
result
Output iterator to the initial position in the destination sequence of at least n elements.
此迭代器不應指向範圍 [first,last) 中的任何元素。

返回值

An iterator to the end of the destination range where elements have been copied.

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// copy_n 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;

  myvector.resize(7);   // allocate space for 7 elements

  std::copy_n ( 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 之間的 距離 成正比:對範圍中的每個元素執行一次賦值操作。

資料競爭

The objects in the range of n elements pointed by first are accessed (each object is accessed exactly once).
The objects in the range between result and the returned value are modified (each object is modified exactly once).

異常

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

另見