首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ 容器元素複製:std::copy 與 std::copy_n

     編輯:關於C++

函式簽名

OutputIterator copy(InputIterator first, InputIterator last, OutputIterator result);
OutputIterator copy_n(InputIterator first, Size n, OutputIterator result);

範例:向量中間插入另一向量

/* main.cpp
 * Created on: 2014年6月17日
 * Author: Spike
 */
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
using namespace std;

int main() {
    vector<int> vi = {1, 2, 3, 4, 0, 0, 0, 8, 9, 10};
    vector<int> vb = {5, 6, 7};
    auto it = vi.begin() + 4;
    copy(vb.begin(), vb.end(), it); // 覆寫 vi[4..6]
    copy(vi.begin(), vi.end(), ostream_iterator<int>(cout, " "));
    cout << endl;
    return 0;
}

輸出

1 2 3 4 5 6 7 8 9 10

注意事項

  • 目標範圍必須有足夠空間,否則行為未定義。
  • copy_n 適合已知元素個數但無終點迭代器的情況。
  • 搭配 back_inserter 可自動擴充目標容器。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved