replace_copy_if


Copy a sequence, replacing values that satisfy a predicate.

Copy the sequence [ first ... last ) to a sequence of the same size starting at result , replacing all elements that satisfy pred with new_value . Return an iterator positioned immediately after the last new element.

Library

Standards<ToolKit>

Declaration


#include <algorithm>

template
  <
  class InputIterator,
  class OutputIterator,
  class Predicate,
  class T
  >
OutputIterator replace_copy_if
  (
  InputIterator first,
  InputIterator last,
  OutputIterator result,
  Predicate pred,
  const T& new_value
  );
  

Complexity

Time complexity is linear, as ( last - first ) comparisons are performed. Space complexity is constant.

Example <ospace/osstd/examples/repcpif1.cpp>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>

bool
odd( int a_ )
  {
  return a_ % 2;
  }

void
main()
  {
  vector< int > v1( 10 );
  for ( int i = 0; i < v1.size(); ++i )
    v1[ i ] = i % 5;
  ostream_iterator< int > iter( cout, " " );
  copy( v1.begin(), v1.end(), iter );
  cout << "\n";
  vector< int > v2( v1.size() );

  replace_copy_if( v1.begin(), v1.end(), v2.begin(), odd, 42 );

  copy( v1.begin(), v1.end(), iter );
  cout << "\n";
  copy( v2.begin(), v2.end(), iter );
  cout << "\n";
  }

0 1 2 3 4 0 1 2 3 4
0 1 2 3 4 0 1 2 3 4
0 42 2 42 4 0 42 2 42 4

Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.