代码改变世界

C++ copy 函数

2012-04-16 17:18  youxin  阅读(10074)  评论(2编辑  收藏  举报

  先看下面的一段代码:

   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<int> v;定义时定义时没有分配空间,copy不成功。应改为vector<int> v(u.size());

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

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

              back_insert;是iterator adapter: 有一个容器作为参数,并且生成一个迭代器,但这个迭代器被称用作目的地时,就会在容器末尾自动的添加元素。所以vector<int> 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.

它使用返回值的:

An output iterator addressing 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 of last).

函数功能类似这样:

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).