×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

std::copy_n() function with example in C++ STL

C++ STL | std::copy_n() function: Here, we are going to learn about the copy_n() function of algorithm header in C++ STL with example.
Submitted by IncludeHelp, on May 20, 2019

C++ STL std::copy_n() function

copy_n() function is a library function of algorithm header, it is used to copy the elements of a container, it copies the given number of elements (n elements) of a container from the given start position to another container from the given beginning position.

Note:To use copy_n() function – include <algorithm> header or you can simple use <bits/stdc++.h> header file.

Syntax

Syntax of std::copy_n() function

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

Parameter(s)

  • iterator source_first – is an iterator pointing to the beginning position of the source container.
  • size – is the total number of elements to be copied.
  • iterator target_start – is the beginning iterator of target container.

Return value

iterator – it is an iterator to the end of the target range where elements have been copied.

Sample Input and Output

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

C++ STL program to demonstrate use of std::copy_n() function

In this example, we are copying n elements of the array elements to the vector.

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

Output

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

Reference: C++ std::copy_n()

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.