Open In App

Different methods to copy in C++ STL | std::copy(), copy_n(), copy_if(), copy_backward()

Last Updated : 15 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Various varieties of copy() exist in C++ STL that allows to perform the copy operations in different manners, all of them having their own use. These all are defined in header <algorithm>. This article introduces everyone to these functions for usage in day-to-day programming. 
1. copy(strt_iter1, end_iter1, strt_iter2) : The generic copy function used to copy a range of elements from one container to another. It takes 3 arguments: 

  • strt_iter1 : The pointer to the beginning of the source container, from where elements have to be started copying.
  • end_iter1 : The pointer to the end of source container, till where elements have to be copied.
  • strt_iter2 : The pointer to the beginning of destination container, to where elements have to be started copying.

2. copy_n(strt_iter1, num, strt_iter2) : This version of copy gives the freedom to choose how many elements have to be copied in the destination container. IT also takes 3 arguments: 

  • strt_iter1 : The pointer to the beginning of the source container, from where elements have to be started copying.
  • num : Integer specifying how many numbers would be copied to destination container starting from strt_iter1. If a negative number is entered, no operation is performed.
  • strt_iter2 : The pointer to the beginning of destination container, to where elements have to be started copying.

CPP




// C++ code to demonstrate the working of copy()
// and copy_n()
  
#include<iostream>
#include<algorithm> // for copy() and copy_n()
#include<vector>
using namespace std;
  
int main()
{
      
   // initializing source vector 
   vector<int> v1 = { 1, 5, 7, 3, 8, 3 };
     
   // declaring destination vectors
   vector<int> v2(6);
   vector<int> v3(6);
     
   // using copy() to copy 1st 3 elements
   copy(v1.begin(), v1.begin()+3, v2.begin());
     
   // printing new vector
   cout << "The new vector elements entered using copy() : ";
   for(int i=0; i<v2.size(); i++)
   cout << v2[i] << " ";
     
   cout << endl;
     
   // using copy_n() to copy 1st 4 elements
   copy_n(v1.begin(), 4, v3.begin());
     
   // printing new vector
   cout << "The new vector elements entered using copy_n() : ";
   for(int i=0; i<v3.size(); i++)
   cout << v3[i] << " ";
    
}


Output: 

The new vector elements entered using copy() : 1 5 7 0 0 0 
The new vector elements entered using copy_n() : 1 5 7 3 0 0 

3. copy_if(): As the name suggests, this function copies according to the result of a “condition“.This is provided with the help of a 4th argument, a function returning a boolean value
This function takes 4 arguments, 3 of them similar to copy() and an additional function, which when returns true, a number is copied, else number is not copied.
4. copy_backward(): This function starts copying elements into the destination container from backward and keeps on copying till all numbers are not copied. The copying starts from the “strt_iter2” but in the backward direction. It also takes similar arguments as copy().

CPP




// C++ code to demonstrate the working of copy_if()
// and copy_backward()
  
#include<iostream>
#include<algorithm> // for copy_if() and copy_backward()
#include<vector>
using namespace std;
  
int main()
{
      
    // initializing source vector 
    vector<int> v1 = { 1, 5, 6, 3, 8, 3 };
          
    // declaring destination vectors
    vector<int> v2(6);
    vector<int> v3(6);
          
    // using copy_if() to copy odd elements
    copy_if(v1.begin(), v1.end(), v2.begin(), [](int i){return i%2!=0;});
          
    // printing new vector
    cout << "The new vector elements entered using copy_if() : ";
    for(int i=0; i<v2.size(); i++)
    cout << v2[i] << " ";
          
    cout << endl;
          
    // using copy_backward() to copy 1st 4 elements
    // ending at second last position
    copy_backward(v1.begin(), v1.begin() + 4, v3.begin()+ 5);
          
    // printing new vector
    cout << "The new vector elements entered using copy_backward() : ";
    for(int i=0; i<v3.size(); i++)
    cout << v3[i] << " ";
  
}


Output: 

The new vector elements entered using copy_if() : 1 5 3 3 0 0 
The new vector elements entered using copy_backward() : 0 1 5 6 3 0 

5. Copy using inserter():

Before copy() operation let us understand the syntax of inserter(). 

inserter() is used as a destination that where we want to copy the elements of the container.

inserter() takes two parameters. The first is a container of arbitrary type and the second is an iterator into the container.

It returns an instance of insert_iterator working on a container of arbitrary type. This wrapper function helps in creating insert_iterator instances. Typing the name of the %iterator requires knowing the precise full type of the container, which can be tedious and impedes generic programming. Using this function lets you take advantage of automatic template parameter deduction, making the compiler match the correct types for you.

The syntax for inserter():

std::inserter(Container& x, typename Container::iterator it);

x: Destination container where the new elements will 
be inserted.
it: Iterator pointing to the insertion point.

Returns: An insert_iterator that inserts elements into 
x at the position indicated by it.

The syntax for copy using inserter():

copy(strt_iter1, end_iter1, inserter(Container& x, typename Container::iterator it));

C++




// C++ code to demonstrate the working of copy() using inserter()
  
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
  
int main()
{
  
    vector<int> v1 = {1, 5, 7, 3, 8, 3};
    vector<int>::iterator itr;
    vector<int> v2;
  
    //using inserter()
    copy(v1.begin(), v1.end(), inserter(v2, itr));
  
    cout << "\nThe new vector elements entered using inserter: ";
    for (int i = 0; i < v2.size(); i++)
        cout << v2[i] << " ";
  
}


Output:

The new vector elements entered using inserter: 1 5 7 3 8 3 

 



Previous Article
Next Article

Similar Reads

std::fixed, std::scientific, std::hexfloat, std::defaultfloat in C++
Formatting in the standard C++ libraries is done through the use of manipulators, special variables or objects that are placed on the output stream. There are two types of floating point manipulators namely, fixed floating point and scientific floating point. These all are defined in header &lt;iostream&gt;. Use of precision : In the default floati
3 min read
copy_n() Function in C++ STL
Copy_n() is the C++ function defined in &lt;algorithm&gt; library in STL. It helps to copy one array element to the new array. Copy_n function allows the freedom to choose how many elements must be copied in the destination container. This function takes 3 arguments, the source array name, the size of the array, and the target array name. Function
2 min read
Array algorithms in C++ STL (all_of, any_of, none_of, copy_n and iota)
From C++11 onwards, some new and interesting algorithms are added in STL of C++. These algorithms operate on an array and are useful in saving time during coding and hence useful in competitive programming as well. all_of() This function operates on whole range of array elements and can save time to run a loop to check each elements one by one. It
4 min read
std::string::length, std::string::capacity, std::string::size in C++ STL
Prerequisite: String in C++ String class is one of the features provided by the Standard template library to us, So it comes up with great functionality associated with it. With these Functionalities, we can perform many tasks easily. Let's see a few of the functionalities string class provides. Header File &lt;string&gt; String Functionalities The
6 min read
std::oct , std::dec and std::hex in C++
This function is used to set the base to octal, decimal or hexadecimal. It sets the basefield format flag for the str stream to the specified base std::oct : When basefield is set to octal, integer values inserted into the stream are expressed in octal base (i.e., radix 8). For input streams, extracted values are also expected to be expressed in oc
2 min read
std::stod, std::stof, std::stold in C++
std::stod() : It convert string into double. Syntax: double stod( const std::string&amp; str, std::size_t* pos = 0 ); double stod( const std::wstring&amp; str, std::size_t* pos = 0 ); Return Value: return a value of type double Parameters str : the string to convert pos : address of an integer to store the number of characters processed. This param
3 min read
std::setbase, std::setw , std::setfill in C++
The useful input/output manipulators are std::setbase, std::setw and std::setfill. These are defined in and are quite useful functions. std::base : Set basefield flag; Sets the base-field to one of its possible values: dec, hex or oct according to argument base.Syntax : std::setbase (int base);decimal : if base is 10hexadecimal : if base is 16octal
3 min read
std::istream_iterator and std::ostream_iterator in C++ STL
The STL is a very powerful library in C++. It is strongly built on the principles of template programming. The STL library has three main components : Containers: These classes define the data structures which are used to contain the data. The data may be stored in linked lists, or trees or arrays. The containers provided in the STL are vector, deq
6 min read
std::bitset::to_ullong and std::bitset::to_ulong in C++ STL
Bitset: A bitset is an array of bool but each Boolean value is not stored separately instead bitset optimizes the space such that each bool takes 1 bit space only, so space taken by bitset bs is less than that of bool bs[N] and vector bs(N). However, a limitation of bitset is, N must be known at compile time, i.e., a constant (this limitation is no
2 min read
std::minmax() and std::minmax_element() in C++ STL
C++ defined functions to get smallest and largest elements among 2 or in a container using different functions. But there are also functions that are used to get both smallest and largest element using a single function, "minmax()" function achieves this task for us. This function is defined in "algorithm" header file. This article would deal in it
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg