C++ copy 函数

先看下面的一段代码:

vector<int> u(10,100);
    vector<int> v;
    copy(u.begin(),u.end(),v.begin());

    for(vector<int>::iterator it=v.begin();it!=v.end();it++)
    {
        cout<<*it<<ends;
    }运行错误!

功能很简单,把vector u复制给v,但运行异常。为什么?

vector v;定义时定义时没有分配空间,copy不成功。应改为vector v(u.size());

如果想使用vector v;有两个方法可以实现同样的功能;

方法一: 使用iterator适配器copy(u.begin(),u.end(),back_inserter(v));

back_insert;是iterator adapter: 有一个容器作为参数,并且生成一个迭代器,但这个迭代器被称用作目的地时,就会在容器末尾自动的添加元素。所以vector v;不必定义大小。

方法二:循环的用push_back来实现

for(vector<int>::iterator it=u.begin();it!=u.end();it++)
     v.push_back(*it);

好了,来看看copy函数正规说明。

template<class InputIterator, class OutputIterator>
   OutputIterator copy(
      InputIterator _First, 
      InputIterator _Last, 
      OutputIterator _DestBeg
   );

Assigns the values of elements from a source range to a destination range, iterating through the source sequence of elements and assigning them new positions in a forward direction.
Parameters

_First
An input iterator addressing the position of the first element in the source range.
_Last
An input iterator addressing the position that is one past the final element in the source range.
_DestBeg
An output iterator addressing the position of the first element in the destination range.

它使用返回值的:

Anoutput iteratoraddressing the position that is one past the final element in the destination range, that is, the iterator addresses_Result+ (_Last_First). 返回指向最后一个元素的迭代器。Returns an iterator to the end of the destination range (which points to the element following the copy oflast).

函数功能类似这样:

template<class InputIterator, class OutputIterator>
  OutputIterator copy ( InputIterator first, InputIterator last, OutputIterator result )
{
  while (first!=last) *result++ = *first++;
  return result;
}

如果想要把一组元素从头到尾向目的地的前端复制,就要用copy_backware函数,用法一模一样,只不过第三个参数为

BidirectionalIterator2 _DestEnd; 目的地的最后一个位置。Copies the elements in the range [first,last) into a range whose end element is result. The function begins by copying *(last-1) into *(result-1), and then follows backwards by the elements preceeding these, until first is reached (and including it).

原文链接: https://www.cnblogs.com/youxin/archive/2012/04/16/2452035.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/47570

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月8日 下午11:34
下一篇 2023年2月8日 下午11:35

相关推荐