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

運行結果:


結論:

1. srcVec.end()相當於src + 7

2. 將容器中的元素從一個區間複製到另一個區間。copy(first_source, Last_source, dest) 進行的是前向處理

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章