From: http://www.cnblogs.com/youxin/archive/2012/04/16/2452035.html
Let's take a look at the following code:
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;} running error!
The function is simple. The vector u is copied to V, but an exception occurs. Why?
Vector <int> V; no space is allocated during definition, and copy fails. Should be changedVector <int> V (U. Size ());
If you want to use vector <int> V, you can use two methods to implement the same function;
Method 1: Use the iterator adapter copy (U. Begin (), u. End (), back_inserter (V ));
Back_insert; is an iterator adapter: a container is used as a parameter to generate an iterator. However, when this iterator is called as a destination, it automatically adds elements to the end of the container. Therefore, vector <int> V does not need to be defined.
Method 2: Use push_back for loop implementation
for(vector<int>::iterator it=u.begin();it!=u.end();it++) v.push_back(*it);
Okay. Let's take a look at the regular description of the copy function.
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.
It uses the following returned values:
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). Return the iterator pointing to the last element. Returns
An iterator to the end of the destination range (which points to the element following the copyLast).
Functions are similar to the following:
template<class InputIterator, class OutputIterator> OutputIterator copy ( InputIterator first, InputIterator last, OutputIterator result ){ while (first!=last) *result++ = *first++; return result;}
If you want to copy a group of elements from start to end to the destination, you need to use the copy_backware function. The usage is the same, but the third parameter is
Bidirectionaliterator2 _ destend; the last location of the destination. Copies the elements in the range[First, last)Into a range whose end element isResult. The function begins by copying* (Last-1)Into* (Result-1), And then follows backwards by the elements preceeding these,FirstIs reached (and including it ).