C++ copy() first 3 elements

Introduction

To copy only the first 3 elements, we would use the appropriate range marked with copy_from_v.begin() and copy_from_v.begin() + 3.

And we only need to reserve the space for 3 elements in the destination vector:

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

int main() //from ww w  .ja  v  a  2s.c  o m
{ 
    std::vector<int> copy_from_v = { 1, 2, 3, 4, 5 }; 
    std::vector<int> copy_to_v(3); 

     std::copy(copy_from_v.begin(), copy_from_v.begin() + 3, copy_to_v. 
     begin()); 

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



PreviousNext

Related