编程第六十、六十一天

来源:互联网 发布:ipc软件 编辑:程序博客网 时间:2024/04/28 06:15

c++ copy()对不同容器复制;关于输出区间与输入区间重叠的讨论

  1. #include <iostream>  
  2. #include <algorithm>  
  3. #include <deque>  
  4.   
  5. using namespace std;  
  6. template<class T>  
  7. struct display  
  8. {  
  9.     void operator()(const T &x)const  
  10.     {  
  11.         cout<<x<<" ";  
  12.     }  
  13. };  
  14.   
  15. int main()  
  16. {  
  17.     //以下复制区间没有问题   
  18.     int ia1[]={0,1,2,3,4,5,6,7,8};  
  19.     copy(ia1+2,ia1+7,ia1);//将下标2-6复制给 1-5  
  20.     for_each(ia1,ia1+9,display<int>()); //2,3,4,5,6,5,6,7,8  
  21.     cout<<endl;  
  22.        
  23.     //输出区间的起点与输入区间重叠,可能会有问题。但本例copy采用memmove()执行实际复制操作   
  24.     int ia2[]={0,1,2,3,4,5,6,7,8};  
  25.     copy(ia2+2,ia2+7,ia2+4);//将下标2-6复制给 4-8  
  26.     for_each(ia2,ia2+9,display<int>()); //0,1,2,3,2,3,4,5,6  
  27.     cout<<endl;  
  28.       
  29.     //以下复制区间没有问题   
  30.     int ia3[]={0,1,2,3,4,5,6,7,8};  
  31.     deque<int> id(ia3,ia3+9);  
  32.     deque<int>::iterator first=id.begin();  
  33.     deque<int>::iterator last=id.end();  
  34.     deque<int>::iterator result=id.begin();  
  35.     ++++first;  
  36.     cout<<*first<<endl;  
  37.     ----last;  
  38.     cout<<*last<<endl;  
  39.     cout<<*result<<endl;  
  40.     copy(first,last,result);  
  41.     for_each(id.begin(),id.end(),display<int>());//2,3,4,5,6,5,6,7,8  
  42.     cout<<endl;  
  43.       
  44.     //以下复制区间存在问题,由于实际复制没有采用memove(),结果错误   
  45.     int ia4[]={0,1,2,3,4,5,6,7,8};  
  46.     deque<int> ide(ia4,ia4+9);  
  47.     deque<int>::iterator first1=ide.begin();  
  48.     deque<int>::iterator last1=ide.end();  
  49.     deque<int>::iterator result1=ide.begin();  
  50.     advance(result1,4);//注意这里跟上面不一样   
  51.     ++++first1;  
  52.     cout<<*first1<<endl;  
  53.     ----last1;  
  54.     cout<<*last1<<endl;  
  55.     cout<<*result1<<endl;  
  56.     copy(first1,last1,result1);  
  57.     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  
  58.     cout<<endl;  
  59.       
  60.       
  61.       
  62.     return 0;  
  63. }