c++ copy()对不同容器复制;关于输出区间与输入区间重叠的讨论
- #include <iostream>
- #include <algorithm>
- #include <deque>
- using namespace std;
- template<class T>
- struct display
- {
- void operator()(const T &x)const
- {
- cout<<x<<" ";
- }
- };
- int main()
- {
- //以下复制区间没有问题
- int ia1[]={0,1,2,3,4,5,6,7,8};
- copy(ia1+2,ia1+7,ia1);//将下标2-6复制给 1-5
- for_each(ia1,ia1+9,display<int>()); //2,3,4,5,6,5,6,7,8
- cout<<endl;
- //输出区间的起点与输入区间重叠,可能会有问题。但本例copy采用memmove()执行实际复制操作
- int ia2[]={0,1,2,3,4,5,6,7,8};
- copy(ia2+2,ia2+7,ia2+4);//将下标2-6复制给 4-8
- for_each(ia2,ia2+9,display<int>()); //0,1,2,3,2,3,4,5,6
- cout<<endl;
- //以下复制区间没有问题
- int ia3[]={0,1,2,3,4,5,6,7,8};
- deque<int> id(ia3,ia3+9);
- deque<int>::iterator first=id.begin();
- deque<int>::iterator last=id.end();
- deque<int>::iterator result=id.begin();
- ++++first;
- cout<<*first<<endl;
- ----last;
- cout<<*last<<endl;
- cout<<*result<<endl;
- copy(first,last,result);
- for_each(id.begin(),id.end(),display<int>());//2,3,4,5,6,5,6,7,8
- cout<<endl;
- //以下复制区间存在问题,由于实际复制没有采用memove(),结果错误
- int ia4[]={0,1,2,3,4,5,6,7,8};
- deque<int> ide(ia4,ia4+9);
- deque<int>::iterator first1=ide.begin();
- deque<int>::iterator last1=ide.end();
- deque<int>::iterator result1=ide.begin();
- advance(result1,4);//注意这里跟上面不一样
- ++++first1;
- cout<<*first1<<endl;
- ----last1;
- cout<<*last1<<endl;
- cout<<*result1<<endl;
- copy(first1,last1,result1);
- for_each(ide.begin(),ide.end(),display<int>());// 0,1,2,3,2,3,2,3,2不是预期的 0,1,2,3,2,3,4,5,6
- cout<<endl;
- return 0;
- }