×

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() 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

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.

Sample Input and Output

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!

Load comments ↻





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