Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to use the replace_if() function in C++

Vinisha Maheshwari

In this shot, we will learn how to use the replace_if() function, which is available in the algorithm library in C++.

The replace_if() function is used to assign new value to all the elements in the range [first, last), for which pred predicate returns true.


The replace_if() method takes the below mentioned parameter:

  • First: Forward iterator for the initial position of the derived range.
  • Last: Forward iterator for the final position of the derived range.
  • Predicate: The unary predicate function that must be satisfied is the value of the element to be replaced.
  • New value: Replacement value.


The replace_if() function doesn’t return anything.


Let’s see the below code snippet.

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

int main()
string s1 = "Example of replace";
cout<<"The string before replace() implementation: " <<s1<<endl;
s1.replace(6, 5, "to all", 6);
cout<<"The string after replace() implementation: "<<s1<<endl;

vector<int> v = { 134,17,20,91,46 };  
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;  
Using replace_if() function in C++


  • In lines 1 to 3, we imported the required header files.
  • In line 6, we made a main function.
  • In line 8, we initialized a string.
  • In line 9, we displayed the message for the string whose characters get replaced with the original string.
  • In line 10, we used the replace() function to replace the string from the 6th index to the 10th index with the replacement string.
  • In line 11, we displayed the message for the replaced string along with it.
  • In line 9, we initialized a vector of the int data type. We used the replace_if() function to replace the multiples of 2 in the vector with 10. We displayed the vector with the replaced values.

In this way, we can use the replace_if() function in C++.



View all Courses

Keep Exploring