正文

STL算法学习(三)2006-07-21 10:42:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/argol/16728.html

分享到:

/*copy   函数原型:          template <class InputIterator,class OutputIterator>          OutputIterator          copy(InputIterator first1,InputIterator last1,OuputIteratoo first2);      功能:将序列[first1,last1)内的元素从由first2指定的开始位置依次进行拷贝。函数         返回拷贝后指向最后一个元素的下一个位置的迭代器。         copy_backward   函数原型:         template <class BidirectionalIterator1,class BidirectionalIterator2>         BidirectionalIterator2         copy_backward(BidirectionalIterator1 first1,BidirectionalIterator1 last1,                       BidirectionalIterator2 last2);                          功能:这也是一个拷贝元素的函数。与copy不同的是,该函数是将从last2-1开始的         元素反相拷贝到区间[first1,last1)内。也就是序列last2-1,last2-2,...,         last2-(last1-first1)将被拷贝。 for_each   函数原型:         template <class InputIterator,class Function>         Function         for_each(InputIterator first,InputIterator last,Function Fun);      功能:对序列[first,last)内的所有元素应用函数Fun.但不能对元素的值进行修改。         因为迭代器的类型是输入迭代器。 */ #include <iostream>#include <vector>#include <algorithm>#include <iterator> using namespace std; class print_elem{      public:                   void operator()(int value)      {           cout << value                << ( line_cnt++%8  ? " " : " \n");      }            static void reset_line_cnt()      { line_cnt = 1 ;}            private:              static int line_cnt;}; int print_elem::line_cnt = 1; int main(){    int ia[] = {0,1,2,3,4,5,6,7};    vector<int> v(ia,ia+8);        /*      原序列            0 1 2 3 4 5 6 7      应用copy将0 1 2 拷贝到3的位置      生成序列           0 1 2 0 1 2 6 7     */    copy(v.begin(),v.begin()+3,v.begin()+3);    copy(v.begin(),v.end(),ostream_iterator<int>(cout, " "));    cout << endl;        /*      应用copy_backward将5,6,7反相拷贝到从元素0开始的位置。      生成序列          0 1 2 3 4 0 1 2    */    copy_backward(v.begin(),v.begin()+3,v.end());    for_each(v.begin(),v.end(),print_elem());        system("pause");    return 0;}

阅读(3697) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册