C++ copy()

Introduction

The std::copy function copies the elements from one container to another.

It can copy a range of elements marked with [starting_position_iterator, ending_position_iterator) from the starting container to a specific position marked with (destination_position_ iterator) in the destination container.

The function is declared inside the <algorithm> header.

Before we copy the elements, we need to reserve enough space in the destination vector by supplying the size to a vector's constructor.

Example:

#include <iostream> 
#include <vector> 
#include <algorithm> 

int main() /*from   ww  w.  j a v a2s .  c o m*/
{ 
    std::vector<int> copy_from_v = { 1, 2, 3, 4, 5 }; 
    std::vector<int> copy_to_v(5); // reserve the space for 5 elements 

    std::copy(copy_from_v.begin(), copy_from_v.end(), copy_to_v.begin()); 

    for (auto el : copy_to_v) 
    { 
        std::cout << el << '\n'; 
    } 
} 

Explanation: we define a source vector called copy_from_v and initialize it with some values.

Then we define a copy_to_v destination vector and reserve enough space for it to hold 5 elements by supplying the number 5 to its constructor.

Then we copy all the elements from the beginning to an end of a source vector to the (beginning of) destination vector.




PreviousNext

Related