天天看點

STL copy()函數用法

#include <iostream>
#include <vector>
#include <iterator>

using namespace std;

int main()
{
    int src[]={1,2,3,4,5,6,7};
    //vector<int> srcVec;
    //srcVec.resize(7);

    vector<int> srcVec(src,src+7);          //注意!7為長度
    ostream_iterator<int> ofile(cout," ");
    //将數值複制到vector裡,參數依次是開始,結束,vector數組的開始
    //(看起來src+7越界了)src+7,表示結束,srcVec.end()相當于src+7
    copy(src,src+7,srcVec.begin());
    
    cout<<"srcVec contains:\n";

    //将數值複制到輸出流中,參數依次是開始,結束,輸出流
    copy(srcVec.begin(),srcVec.end(),ofile);

    cout<<endl;

    //将數組向左移動兩位
    copy(src+2,src+7,src);
    cout<<"shifting array sequence left by 2"<<endl;
    copy(src,src+7,ofile);
    cout<<endl;


    //另一種方法,注意觀察copy()中第二個參數
    //srcVec.end()相當于src+7
    //将數組向左移動兩位
    copy(srcVec.begin()+2,srcVec.end(),srcVec.begin());
    cout<<"shifting array sequence left by 2"<<endl;
    copy(srcVec.begin(),srcVec.end(),ofile);
    cout<<endl;
    return 0;
}      
STL copy()函數用法