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:
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; }
main
function.replace()
function to replace the string from the 6th index to the 10th index with the replacement string.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++.
RELATED TAGS
CONTRIBUTOR
View all Courses