copy
拷贝,把源迭代器区间的值拷贝到目的迭代器。使用者保证目的空间足够。时间复杂度O(n)。
函数声明如下:
template<class InputIterator, class OutputIterator>
OutputIterator copy(
InputIterator _First, //源开始迭代器
InputIterator _Last, //源结束迭代器
OutputIterator _DestBeg //目的开始迭代器
);
源码剖析
template<class InputIterator, class OutputIterator>
OutputIterator copy(
InputIterator first, //源开始迭代器
InputIterator last, //源结束迭代器
OutputIterator destBeg //目的开始迭代器
)
{
while(first != last) //遍历源迭代器区间
{
*destBeg = *first; //拷贝元素值
++destBeg; //迭代器自增
++first;
}
return destBeg;
}
应用举例
//输出vector的所有元素
template<typename T>
void Show(const vector<T>& v)
{
for (auto x : v)
cout << x << " ";
cout << endl;
}
int main()
{
vector<int>v1{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
vector<int>v2;
//下面这句可以使用 v2 = v1;
copy(v1.begin(),v1.end(),back_inserter(v2));//把v1的元素全部拷贝到v2,注意v2需要安插迭代器
cout << "拷贝v1后,v2:"; Show(v2);
copy(v1.begin()+3,v1.begin()+6,v2.begin());//拷贝部分数据,这个不能使用 =
cout << "拷贝部分数据后,v2:"; Show(v2);
return 0;
}
本篇完!