#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
//拷贝区间
int main()
{
/************************************************************************/
//copy
/************************************************************************/
//copy将input range[first,last) 复制到output range[DestBeg,DestBeg+(last-frist))内
//注意:copy函数不能用来将元素安插于空的Container中,例如空的vector、list中,需要搭配adapter来完成copy操作
/*
template<class InputIterator, class OutputIterator>
OutputIterator copy(
InputIterator _First,
InputIterator _Last,
OutputIterator _DestBeg
);
*/
int A[] = {1,3,4,5,7,8};
const int N = sizeof(A) / sizeof(int);
std::vector<int> ivSource(A, A + N);//等价于 std::copy(A, A + N, ivSource.begin());
std::vector<int> ivDest1;
std::vector<int> ivDest2(N);
#ifdef _DEBUG
std::vector<int> ii(5,3);//3 3 3 3 3
for(std::vector<int>::iterator it = ii.begin();it != ii.end();++it)
std::cout << *it << " ";
std::cout << std::endl;
#endif
std::copy(ivSource.begin(), ivSource.end(), ivDest1.begin());
std::cout << ivDest1.size() << std::endl;//terminate ,因为ivDest1原本为空
std::copy(ivSource.begin(), ivSource.end(), ivDest2.begin());
std::cout << ivDest2.size() << std::endl;//6
std::copy(ivSource.begin(), ivSource.end(), back_inserter(ivDest1));
std::cout << ivDest1.size() << std::endl;//6
std::copy(std::begin(A), std::end(A), std::ostream_iterator<int>(std::cout, " "));//1 3 4 5 7 8
//等价于 std::copy(A, A + N, std::ostream_iterator<int>(std::cout, " "));//1 3 4 5 7 8
std::cout << std::endl;
/************************************************************************/
//copy_backward
/************************************************************************/
//copy_backward类似copy函数,但是copy_backward从后往前复制
//即Last复制到DestEnd,Last-1复制到DestEnd-1,依次类推...
/*
template<class BidirectionalIterator1, class BidirectionalIterator2>
BidirectionalIterator2 copy_backward(
BidirectionalIterator1 _First,
BidirectionalIterator1 _Last,
BidirectionalIterator2 _DestEnd
);
*/
int B[15] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
std::copy_backward(B, B + 10, B + 15);
std::copy(B, B + 15, std::ostream_iterator<int>(std::cout, " "));
//1 2 3 4 5 1 2 3 4 5 6 7 8 9 10
std::cout << std::endl;
//注意点:
//在对于两区间存在重叠的情况下,copy和copy_backward的使用情况刚好相反
//1、如果output range的开头与input range重叠,则不能使用copy函数,
// 但如果output range的尾部与input range重叠,则可以使用copy函数
//2、如果output range的尾部与input range重叠,则不能使用copy_backward函数,
// 但如果output range的开部与input range重叠,则可以使用copy_backward函数
return 0;
}
====================打个广告,欢迎关注====================
QQ: | 412425870 |
csdn博客: | http://blog.csdn.net/caychen |
码云: | https://gitee.com/caychen/ |
github: | https://github.com/caychen |
点击群号或者扫描二维码即可加入QQ群: | |