algorithm::copy_n()
描述 (Description)
C ++函数std::algorithm::copy_n()前n个数字复制到新位置。 如果n的值为负,则函数不执行任何操作。
声明 (Declaration)
以下是std :: algorithm :: copy_n()函数形式std :: algorithm头的声明。
C++11
template <class InputIterator, class Size, class OutputIterator>
OutputIterator copy_n (InputIterator first, Size n, OutputIterator result);
参数 (Parameters)
first - 将迭代器输入到搜索序列的初始位置。
n - 要复制的元素数。
result - 将迭代器输出到新序列中的初始位置。
返回值
返回到目标范围末尾的迭代器,其中元素已被复制。
异常 (Exceptions)
如果元素赋值或迭代器上的操作抛出异常,则抛出异常。
请注意,无效参数会导致未定义的行为。
时间复杂
在第一个到最后一个之间的距离线性。
例子 (Example)
以下示例显示了std :: algorithm :: copy_n()函数的用法。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(void) {
vector<int> v1 = {1, 2, 3, 4, 5};
vector<int> v2(3);
copy_n(v1.begin(), 3, v2.begin());
cout << "Vector v2 contains following elements" << endl;
for (auto it = v2.begin(); it != v2.end(); ++it)
cout << *it << endl;
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 -
Vector v2 contains following elements
1
2
3