本文内容来自C++Plus,本文只是本人的总结和翻译而已。本人只是C++的搬运工。
原文传送门:http://www.cplusplus.com/reference/algorithm/copy_n/
copy_n算法:copy 元素
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的位置开始copy,n个元素到指定的容器位置中,如果n<=0就啥都不会做。
测试代码如下:
// 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;
}