当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ std::copy_n()用法及代码示例


C++ STL std::copy_n() 函数

copy_n() 函数是算法头的库函数,用于复制一个容器的元素,它将一个容器的给定数量的元素(n 个元素)从给定的开始位置复制到另一个容器从给定的开始位置。

注意:使用 copy_n() 函数 - 包括<algorithm>标题或者您可以简单使用<bits/stdc++.h>头文件。

std::copy_n() 函数的语法

    std::copy_n(iterator source_first, size, iterator target_start);

参数:

  • iterator source_first- 是指向源容器开始位置的迭代器。
  • size- 是要复制的元素总数。
  • iterator target_start- 是目标容器的起始迭代器。

返回值: iterator- 它是指向已复制元素的目标范围末尾的迭代器。

例:

    Input:
    //declaring & initializing an int array
    int arr[] = { 10, 20, 30, 40, 50 };
    
    //vector declaration
    vector<int> v1(5);
    
    //copying 5 array elements to the vector
    copy_n(arr, 5, v1.begin());

    Output:
    //if we print the value
    arr:10 20 30 40 50
    v1:10 20 30 40 50

用于演示 std::copy_n() 函数使用的 C++ STL 程序

在这个例子中,我们将数组元素的 n 个元素复制到向量中。

//C++ STL program to demonstrate use of
//std::copy_n() function
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main()
{
    //declaring & initializing an int array
    int arr[] = { 10, 20, 30, 40, 50 };
    //vector declaration
    vector<int> v1(5);

    //copying 5 array elements to the vector
    copy_n(arr, 5, v1.begin());

    //printing array
    cout << "arr:";
    for (int x:arr)
        cout << x << " ";
    cout << endl;

    //printing vector
    cout << "v1:";
    for (int x:v1)
        cout << x << " ";
    cout << endl;

    return 0;
}

输出

arr:10 20 30 40 50
v1:10 20 30 40 50

参考:C++ std::copy_n()



相关用法


注:本文由纯净天空筛选整理自 std::copy_n() function with example in C++ STL。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。