Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

copy_if
c++
communitycreator

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

Harsh Jain

The copy_if() function is available in the <algorithm.h> header file in C++. This function is used to copy the elements within the specified range to a result vector based on a condition. The condition needs to be true for the elements to be copied.

Parameters

The copy_if() function accepts the following parameters:

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

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

  • condition: This is a unary functionfunction that accepts one argument and returns a Boolean value indicating whether the condition is satisfied or not.

  • result: This is an iterator that points to the new array or vector 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).

Return

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

Code

Let’s have a look at the code below:

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

bool IsNonNegative(int a){
  return a > 0;
}

int main() {
  int arr[] = {10,-20,30,40,-50,60,-70};
  vector<int> vec (7);

  copy_if(arr, arr+7, vec.begin(), IsNonNegative);

  cout << "Copied Vector contains: ";
  for (int x: vec)
    cout << x << " ";

  return 0;
}
Use copy_if() function in C++

Explanation:

  • From lines 1 to 3, we import the required header files.

  • From lines 6 to 8, we create a unary function that returns true if the number is greater than zero.

  • In line 11, we create an array of integers.

  • In line 12, we create the vector where we want to store the copied data from the array.

  • In line 14, we call the copy_if() function and pass the required parameters. We pass the vec.begin() as the starting address of our result vector.

  • From lines 16 to 18, we print the copied data using a for loop. You can notice that at the end there are many zeros printed. To avoid that, after copying the elements, we can resize the result vector to avoid any extra memory usage.

This way we can use the copy_if() function to copy the elements based on the conditions.

RELATED TAGS

copy_if
c++
communitycreator
RELATED COURSES

View all Courses

Keep Exploring