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).

异常

如果元素赋值或迭代器操作抛出异常,则会抛出异常。
请注意,无效参数会导致未定义行为

另见