copy函数是STL中常用函数之一。
copy函数原型:
template<class InputIterator, class OutputIterator> OutputIterator copy( InputIterator _First, InputIterator _Last, OutputIterator _DestBeg );
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 fi irst elementn the destination range.
在这里我们需要注意一点:_Last参数的意思:指向最后一个元素的下一个位置。
Return Value:
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 ).
Remarks:
The source range must be valid and there must be sufficient space at the destination to hold all the elements being copied.
Because the algorithm copies the source elements in order beginning with the first element, the destination range can overlap with the source range provided the _Last position of the source range is not contained in the destination range. copy can be used to shift elements to the left but not the right, unless there is no overlap between the source and destination ranges. To shift to the right any number of positions, use the copy_backward algorithm.
Examples:
#include <vector> #include <algorithm> #include <iostream> int main() { using namespace std; vector <int> v1, v2; vector <int>::iterator Iter1, Iter2; int i; for ( i = 0 ; i <= 5 ; i++ ) v1.push_back( 10 * i ); int ii; for ( ii = 0 ; ii <= 10 ; ii++ ) v2.push_back( 3 * ii ); cout << "v1 = ( " ; for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ ) cout << *Iter1 << " "; cout << ")" << endl; cout << "v2 = ( " ; for ( Iter2 = v2.begin( ) ; Iter2 != v2.end( ) ; Iter2++ ) cout << *Iter2 << " "; cout << ")" << endl; // To copy the first 3 elements of v1 into the middle of v2 copy( v1.begin( ), v1.begin( ) + 3, v2.begin( ) + 4 ); cout << "v2 with v1 insert = ( " ; for ( Iter2 = v2.begin( ) ; Iter2 != v2.end( ) ; Iter2++ ) cout << *Iter2 << " "; cout << ")" << endl; // To shift the elements inserted into v2 two positions // to the left copy( v2.begin( )+4, v2.begin( ) + 7, v2.begin( ) + 2 ); cout << "v2 with shifted insert = ( " ; for ( Iter2 = v2.begin( ) ; Iter2 != v2.end( ) ; Iter2++ ) cout << *Iter2 << " "; cout << ")" << endl; return 0; }
运行结果:
v1 = ( 0 10 20 30 40 50 )
v2 = ( 0 3 6 9 12 15 18 21 24 27 30 )
v2 with v1 insert = ( 0 3 6 9 0 10 20 21 24 27 30 )
v2 with shifted insert = ( 0 3 0 10 20 10 20 21 24 27 30 )
另一个例子:
#include <iostream> #include <vector> #include <algorithm> #include <iterator> using namespace std; int main() { int n=10; vector<int> v; for(int i=0;i<n;i++) { v.push_back(i); } random_shuffle (v.begin(),v.end());//把容器内的元素捣乱 copy(v.begin(),v.end(),ostream_iterator<int>(cout,"\n")); return 0; }
运行结果:
4
3
0
2
6
7
8
9
5
1