C++ Algorithm Library - copy_if() Function



Description

The C++ function std::algorithm::copy_if() copies a range of elements to a new location if predicate returns true for value.

Declaration

Following is the declaration for std::algorithm::copy_if() function form std::algorithm header.

C++11

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

Parameters

  • first − Input iterators to the initial positions of the searched sequence.

  • last − Input iterators to the final positions of the searched sequence.

  • result − Output iterator to the initial position in the new sequence.

  • pred − Unary predicate which takes an argument and return a bool value.

Return value

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

Exceptions

Throws an exception if either element assignment or an operation on an iterator throws exception.

Please note that invalid parameters cause undefined behavior.

Time complexity

Linear in the distance between first to last.

Example

The following example shows the usage of std::algorithm::copy_if() function.

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

using namespace std;

bool predicate(int n) {
   return (n %2 != 0);
}

int main(void) {
   vector<int> v1 = {1, 2, 3, 4, 5};
   vector<int> v2(3);

   copy_if(v1.begin(), v1.end(), v2.begin(), predicate);

   cout << "Following are the Odd numbers from vector" << endl;

   for (auto it = v2.begin(); it != v2.end(); ++it)
      cout << *it << endl;

   return 0;
}

Let us compile and run the above program, this will produce the following result −

Following are the Odd numbers from vector
1
3
5
algorithm.htm
Advertisements