replace_if() Function in C++

«
»
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.

  1. /*
  2.  * C++ Program to demonstrate the replace_if() algorithm
  3.  */
  4. #include <iostream>
  5. #include <algorithm>
  6. #include <vector>
  7. using namespace std;
  8.  
  9. void print(vector<int>& v)
  10. {
  11.     for(int i = 0; i < v.size(); i++)
  12.         cout << v[i] << " ";
  13.     cout << endl;
  14. }
  15.  
  16. bool IsEven(int i)
  17. {
  18. 	return ((i%2) == 0);
  19. }
  20.  
  21. int main()
  22. {
  23.     vector<int> v = {1, 2, 3, 4 , 5, 6, 7, 8, 9, 10};
  24.  
  25.     cout << "v : ";
  26.     print(v);
  27.     // Replace even numbers with 1
  28.     replace_if (v.begin(), v.end(), IsEven, 1);
  29.     cout << "After replacing even elements with 1\n";
  30.     cout << "v : ";
  31.     print(v);
  32. }

$ 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.

Note: Join free Sanfoundry classes at Telegram or Youtube
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.