Home » C++ STL

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

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

C++ STL std::copy() function

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

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

Syntax of std::copy() function

    std::copy(iterator source_first, iterator source_end, iterator target_start);

Parameter(s):

  • iterator source_first, iterator source_end – are the iterator positions of the source container.
  • iterator target_start – is the beginning iterator of the target container.

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

Example:

    Input:
    //declaring & initializing an int array
    int arr[] = { 10, 20, 30, 40, 50 };
    
    //vector declaration
    vector<int> v1(5);
    
    //copying array elements to the vector
    copy(arr, 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() function

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

//C++ STL program to demonstrate use of
//std::copy() 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 array elements to the vector
    copy(arr, 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()






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.