先看下面的一段代碼:
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.
- _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).
