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;
- }