template<class InputIterator, class OutputIterator>
OutputIterator copy(
InputIterator _First,
InputIterator _Last,
OutputIterator _DestBeg
);
_First
An input iterator addressing the position of the firstelement in the source range.
_Last
An input iterator addressing the position that is onepast the final element in the source range.
_DestBeg
An output iterator addressing the position of the firstelement in the destination range.
例子:http://msdn.microsoft.com/zh-cn/library/vstudio/x9f6s1wf%28v=vs.100%29.aspx
copy作用就是把_First 到_Last之間的資料複制到由 _DestBeg指向第一個元素的位址。
例子:
#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;
}
輸出:
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 )
可以和ostream_iterator<Type>(&ostream,"界定符");結合使用。
ostream_iterator(
ostream_type& _Ostr
);
ostream_iterator(
ostream_type& _Ostr,
const CharType* _Delimiter
);
如:
copy(v1.begin(),v1.end(),ostream_iterator<int>(cout,"\n"));會對資料進行逐個輸出