STL之copy

需要的头文件:
numeric

源码:

//源码比较复杂,不予列出
//有兴趣的可以参考sgi stl的源码

作用:
将输入区间[first,last)内元素复制到区间[result,result+(last-first))内

例子:

//例子只给出使用方法,有很多细节不予阐述
//具体细节参见 《STL源码剖析》
 #include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
#include <deque>

using namespace std;

template <typename T>
struct display
{
    void operator()(const T& x)
    {
        cout << x << " ";
    }
};

int main()
{
    {
        int ia[] = { 0,1,2,3,4,5,6,7,8, };
        //输出区间与输入区间不重叠,没有冲突
        copy(ia + 2, ia + 7, ia);
        for_each(begin(ia), end(ia), display<int>()); cout << endl;
        //2 3 4 5 6 5 6 7 8 
    }
    //////////////////////////////////////////////////
    {
        int ia[] = { 0,1,2,3,4,5,6,7,8, };
        //输出区间与输入区间重叠,有可能冲突
        copy(ia + 2, ia + 7, ia+4);
        for_each(begin(ia), end(ia), display<int>()); cout << endl;
        //0 1 2 3 2 3 4 5 6 
        //本例正确,底层调用memmove,正确复制

    }
    //////////////////////////////////////////////////
    {
        int ia[] = { 0,1,2,3,4,5,6,7,8, };
        //deque 具有 has no trivial assignment operator
        deque<int> id( begin(ia), end(ia) );
        auto first = id.begin();
        auto last = id.end();
        auto result = id.begin();
        cout << *result << endl;    //0
        ++++first;                  //advance(first,2)
        cout << *first << endl;     //2
        ----last;                   //advance(last,2)
        cout << *last << endl;      //7

        //输出区间的终点与输入区间不重叠,没有有冲突
        copy( first, last, result );
        for_each(id.begin(), id.end(), display<int>()); cout << endl;
        //2 3 4 5 6 5 6 7 8 
    }
    //////////////////////////////////////////////////
    {
        int ia[] = { 0,1,2,3,4,5,6,7,8, };
        //deque 具有 has no trivial assignment operator
        deque<int> id(begin(ia), end(ia));
        auto first = id.begin();
        auto last = id.end();
        auto result = id.begin();
        advance( result, 4 );
        cout << *result << endl;    //4
        ++++first;                  //advance(first,2)
        cout << *first << endl;     //2
        ----last;                   //advance(last,2)
        cout << *last << endl;      //7

        //输出区间的终点与输入区间重叠,有可能冲突
        copy(first, last, result);
        for_each(id.begin(), id.end(), display<int>()); cout << endl;
        //0 1 2 3 2 3 2 3 2
        //本例错误,因为copy算法不再使用memmove(因为deque 具有 has no trivial assignment operator)
        //请注意,使用vector代替deque进行测试,复制结果将是正确的,因为vector的迭代器就是个原生指针
    }



    return 0;
}

注意:

  • 注意输入区间和输出区间重叠的问题。十分重要
  • 最好都可以去看看《STL源码剖析》关于这一知识点的讲解,注意区分has no trivial assignment operator 与 has trivial assignment operator。
  • copy十分注重效率
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值