名称: copy(InputIterator first, InputIterator last, OutputIterator result)
说明: 复制一定范围的元素
用法: 将范围[first,last]中的元素复制到从结果开始的范围中,函数返回一个迭代器到目标范围的末尾(它指向最后一个复制的元素后面的元素),通常用来进行数组的复制等。
函数原型
OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result)
{
while (first!=last) {
*result = *first;
++result; ++first;
}
return result;
}
示例:
官方示例
// 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;
}
运行结果:
用法1
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main ()
{
int myints[]={10,20,30,40,50,60,70};
int copyArray[7];
copy(myints,myints+7,copyArray);
cout<<"copyArray:";
for(int i=0;i<7;i++)
{
cout<<copyArray[i]<<" ";
}
return 0;
}
运行结果: