當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ copy_n()用法及代碼示例

Copy_n()是STL中<algorithm>庫中定義的C++函數。它有助於將一個數組元素複製到新數組。 Copy_n 函數允許自由選擇必須在目標容器中複製多少元素。該函數有 3 個參數:源數組名稱、數組大小和目標數組名稱。

函數模板:

template <class InputIterator, class Size, class OutputIterator>
OutputIterator copy_n (InputIterator start_limit, Size count, OutputIterator result);

參數:

  • start_limit - 指向要複製的元素範圍開頭的輸入迭代器。
    count- 要複製的元素數量。
    result- 將迭代器輸出到新容器中的初始位置。

時間複雜度:在)
輔助空間:在)

示例 1:

C++


// C++ code to demonstrate the 
// working of copy_n() function 
// Used with array 
#include <algorithm> 
#include <iostream> 
  
using namespace std; 
  
int main() 
{ 
    // Initializing the array 
    int ar[6] = { 8, 2, 1, 7, 3, 9 }; 
  
    // Declaring second array 
    int ar1[6]; 
  
    // Using copy_n() to copy contents 
    copy_n(ar, 6, ar1); 
  
    // Displaying the new array 
    cout << "The new array after copying is : "; 
    for (int i = 0; i < 6; i++) { 
        cout << ar1[i] << " "; 
    } 
  
    return 0; 
}
輸出
The new array after copying is : 8 2 1 7 3 9 

下麵的代碼演示了如何使用向量的 copy_n() 函數。

示例 2:

C++


// C++ code to demonstrate the 
// working of copy_n() function 
// Used with vector 
#include <algorithm> 
#include <iostream> 
#include <vector> 
  
using namespace std; 
  
int main() 
{ 
  
    // initializing the source vector 
    vector<int> v1 = { 8, 2, 1, 7, 3, 9 }; 
  
    // declaring destination vectors 
    vector<int> v2(6); 
  
    // using copy_n() to copy first 3 elements 
    copy_n(v1.begin(), 3, v2.begin()); 
  
    // printing new vector 
    cout << "The new vector after copying is : "; 
    for (int i = 0; i < v2.size(); i++) { 
        cout << v2[i] << " "; 
    } 
  
    return 0; 
}
輸出
The new vector after copying is : 8 2 1 0 0 0 


相關用法


注:本文由純淨天空篩選整理自pushpeshrajdx01大神的英文原創作品 copy_n() Function in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。