replace_if


Replace specified values that satisfy a predicate.

Replace every element in the range [ first ... last ) that satisfies pred with new_value .

Library

Standards<ToolKit>

Declaration


#include <algorithm>

template< class ForwardIterator, class Predicate, class T >
void replace_if
  (
  ForwardIterator first,
  ForwardIterator last,
  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/replif1.cpp>
#include <iostream>
#include <algorithm>
#include <vector>

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

void
main()
  {
  vector< int > v1( 10 );
  int i;
  for ( i = 0; i < v1.size(); ++i )
    {
    v1[ i ] = i % 5;
    cout << v1[ i ] << ` `;
    }
  cout << "\n";

  replace_if( v1.begin(), v1.end(), odd, 42 );

  for ( i = 0; i < v1.size(); ++i )
    cout << v1[ i ] << ` `;
  cout << "\n";
  }

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.