C++ Standard Library C++ STL Library

C++ <algorithm> - copy_if() Function



The C++ algorithm::copy_if function is used to copy all elements in the range [first, last) to the range starting at result, for which the unary function pred returns true.

Syntax

template <class InputIterator, class OutputIterator, class UnaryPredicate>
  OutputIterator copy_if (InputIterator first, 
                          InputIterator last,
                          OutputIterator result, 
                          UnaryPredicate pred);

Parameters

first Specify initial position of the input iterator. The range used is [first,last).
last Specify final position of the input iterator. The range used is [first,last).
result Specify initial position of the output iterator where the result to be stored.
pred Specify an unary function that accepts an element in the range as argument, and returns a value convertible to bool. The element will be copied if the function returns true.

Return Value

Returns an iterator pointing to the element that follows the last element copied to result sequence.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the algorithm::copy_if function is used to copy all even elements from an array to a vector.

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

bool isEven (int i) {return (i%2==0);}

int main (){
  int arr[] = {10, 11, 12, 13, 14, 15};
  vector<int> vec = {1, 1, 1, 1, 1};
  vector<int>::iterator it;

  //copy first even elements from array to vector
  copy_if(arr, arr+6, vec.begin(), isEven);

  cout<<"arr contains:";
  for(int i = 0; i < 5; ++i)
    cout<<" "<<arr[i];

  cout<<"\nvec contains:";
  for(it = vec.begin(); it != vec.end(); ++it)
    cout<<" "<<*it;

  return 0;
}

The output of the above code will be:

arr contains: 10 11 12 13 14
vec contains: 10 12 14 1 1

❮ C++ <algorithm> Library