This C++ program demonstrates the replace() algorithm. The replace() function takes four arguments – iterator to the beginning of the container, iterator to the end of the container, element to be replaced, and the element to be replaced with.
Here is the source code of the C++ program which demonstrates the replace() algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/** C++ Program to demonstrate the replace_if() algorithm*/#include <iostream>#include <algorithm>#include <vector>using namespace std;
void print(vector<int>& v)
{for(int i = 0; i < v.size(); i++)
cout << v[i] << " ";
cout << endl;
}bool IsEven(int i)
{return ((i%2) == 0);
}int main()
{vector<int> v = {1, 2, 3, 4 , 5, 6, 7, 8, 9, 10};
cout << "v : ";
print(v);
// Replace even numbers with 1replace_if (v.begin(), v.end(), IsEven, 1);
cout << "After replacing even elements with 1\n";
cout << "v : ";
print(v);
}
$ gcc test.cpp $ a.out v : 1 2 3 4 5 6 7 8 9 10 After replacing even elements with 1 v : 1 1 3 1 5 1 7 1 9 1
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Related Posts:
- Practice Programming MCQs
- Apply for Computer Science Internship
- Apply for C++ Internship
- Check Programming Books
- Check C++ Books