Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

remove_copy
c++
communitycreator

How to use the remove_copy() function in C++

Harsh Jain

The remove_copy() function in C++ helps copy the elements from a vector/array and remove all the occurrences of a value within that vector/array. This function is available in the <algorithm.h> header file.

Syntax

The syntax of remove_copy() function is as shown below:

OutputIterator remove_copy (InputIterator first, InputIterator last, OutputIterator result, const T& val)

where,

  • OutputIterator is the iterator pointing to the result vector.
  • InputIterator is the iterator pointing to the input array.
  • T is the template denoting the data type of the value that we want to remove.

Parameters

The remove_copy() function accepts the following parameters:

  • first: This is an iterator that points to the array’s first index or vector from where we want to perform the remove operation.

  • last: This is an iterator that points to the last index of the array or vector till where we want to perform the remove operation.

  • result: This is an iterator that points to the start of the new array or vector to where we want to store the copied elements. The size of the result should be large enough to accommodate the elements in the range [first, last).

  • value: This is the value that we want to remove within the range [first, last) in the given array or vector.

Return

The remove_copy() function returns an iterator that points to the end of the result vector where the last element has been copied.

Code

Let’s look at the code now.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main () {

  vector<int> vec = { 10, 20, 30, 40, 30, 60, 70, 30, 100 };
  vector<int> result (9);
  
  remove_copy(vec.begin(), vec.end(), result.begin(), 30);
  
  for (int x: result)
    cout << x << " ";
  
  return 0;
}
Use remove_copy() function in C++

Explanation:

  • From lines 1 to 3, we import the required header files.
  • In line 8, we create a vector containing integers.
  • In line 9, we create the vector where we want to store the copied data from the vector.
  • In line 11, we call the remove_copy() function and pass the required parameters. Note that we are passing the start of result as result.begin(), and we want to remove all occurrences of the element 30.
  • In lines 13 and 14, we print the result vector. (You can observe that there are many 0s in the vector, so we can also resize the vector to avoid this.

So, in this way, we can use the remove_copy() function in C++.

RELATED TAGS

remove_copy
c++
communitycreator
RELATED COURSES

View all Courses

Keep Exploring