Algorithm Replace If Function - C++ Programming Tutorial
C++ Course / STL Algorithm / Algorithm Replace If Function

Algorithm Replace If Function

BLUF: Mastering Algorithm Replace If Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Algorithm Replace If Function

C++ is renowned for its efficiency. Learn how Algorithm Replace If Function enables low-level control and high-performance computing in the tutorial below.

The C++ replaceif function is utilized to update elements within the range [first, last) with a newvalue when the pred predicate evaluates to true.

This function evaluates every item within a given range and substitutes it if it meets a specified condition.

Syntax

Example

template <class ForwardIterator, class UnaryPredicate, class T>
void replace_if (ForwardIterator first, ForwardIterator last,
UnaryPredicate pred, const T& new_value );

Parameter

A forward iterator indicating the starting position within the range where elements are being substituted.

last : A forward iterator that indicates the ultimate position within the range where elements are being substituted.

The unary predicate function that needs to be met is the requirement for the value of the element to be substituted.

The updated value assigned to the elements that meet the condition of the predicate.

Return value

Complexity

The time complexity increases linearly with the distance between the first and last elements. It applies a given function to each element and assigns the result to those that match the specified criteria.

Data races

The elements within the range [first1, last1) are accessed and may be altered.

Exception safety

This function will raise an exception if any errors occur during the execution of the predicates, element assignments, or iterator operations.

Please be aware that providing incorrect parameters can result in undefined behavior.

Example 1

Let's explore a basic example to illustrate the application of replace_if:

Example

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

using namespace std;

int main() {
  vector<int> v = { 3,1,2,1,2 };

  replace_if(v.begin(), v.end(),
    [](int x) { return x%2 != 0; }, 10);

  for_each(v.begin(), v.end(),
    [](int x) { cout << x << ","; });
    
    return 0;
}

Output:

Output

10,10,2,10,2,

The example above identifies odd values within vector v and substitutes each identified element with the value 10.

Example 2

Let's see another simple example:

Example

#include <vector>  
#include <algorithm>  
#include <iostream>  
  
bool greater6 ( int value ) {  
   return value >6;  
}  
  
int main( ) {  
   using namespace std;  
   vector <int> v1;  
   vector <int>::iterator Iter1;  
  
   int i;  
   for ( i = 0 ; i <= 9 ; i++ )  
      v1.push_back( i );  
  
   int ii;  
   for ( ii = 0 ; ii <= 3 ; ii++ )  
      v1.push_back( 7 );  
  
   random_shuffle ( v1.begin( ), v1.end( ) );  
   cout << "The original vector v1 is:\n ( " ;  
   for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )  
      cout << *Iter1 << " ";  
   cout << ")." << endl;  
  
   // Replace elements satisfying the predicate greater6  
   // with a value of 70  
   replace_if ( v1.begin( ), v1.end( ), greater6 , 70);  
  
   cout << "The vector v1 with a value 70 replacing those\n "  
        << "elements satisfying the greater6 predicate is:\n ( " ;  
   for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )  
      cout << *Iter1 << " ";  
   cout << ")." << endl;  
   
   return 0;
}

Output:

Output

The original vector v1 is:
 ( 4 7 7 7 0 5 7 1 6 9 3 7 8 2 ).
The vector v1 with a value 70 replacing those
 elements satisfying the greater6 predicate is:
 ( 4 70 70 70 0 5 70 1 6 70 3 70 70 2 ).

In the scenario mentioned, vector v1 is updated with a value of 70 for elements that meet the condition of being greater than 6.

Example 3

Let's see another simple example:

Example

#include <iostream>
#include <vector>
#include <algorithm>
 
using namespace std;
 
bool isDivisibleByThree
(
  int n //in
)
{
  return (n%3 == 0);
}
 
int main()
{
  int a[] = {1, 2, 2, 3, 4, 5, 2, 6};
  vector<int> v(a, a+8);
 
  cout <<"\nHere are the values in the vector:\n";
  for (vector<int>::size_type i=0; i<v.size(); i++)
    cout <<v.at(i)<<" ";
 
  cout <<"\nNow we replace all values divisble by 3 with 123.";
  replace_if(v.begin(), v.end(), isDivisibleByThree, 123);
 
  cout <<"\nHere are the revised contents of the vector:\n";
  for (vector<int>::size_type i=0; i<v.size(); i++)
    cout <<v.at(i)<<" ";
 
  return 0;
}

Output:

Output

Here are the values in the vector:
1 2 2 3 4 5 2 6 
Now we replace all values divisible by 3 with 123.
Here are the revised contents of the vector:
1 2 2 123 4 5 2 123

Example 4

Let's see another simple example:

Example

#include <iostream>     // std::cout
#include <algorithm>    // std::replace_if
#include <vector>       // std::vector

using namespace std;

bool IsOdd (int i) { return ((i%2)==1); }

int main () {
  vector<int> myvector;

  // set some values:
  for (int i=1; i<10; i++) myvector.push_back(i);               // 1 2 3 4 5 6 7 8 9

  replace_if (myvector.begin(), myvector.end(), IsOdd, 0); // 0 2 0 4 0 6 0 8 0

  cout << "myvector contains:";
  for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    cout << ' ' << *it;
  cout << '\n';

  return 0;
}

Output:

Output

myvector contains: 0 2 0 4 0 6 0 8 0

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience