remove_if() Function in C++

«
»
This C++ program demonstrates the remove_if() algorithm. The program creates a vector of strings and removes elements whose first letter is ‘A’ using predicate which is passed as a parameter to the remove_if algorithm which removes elements for which the predicate returns true.

Here is the source code of the C++ program which demonstrates the remove_if() 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 remove_if algorithm
  3.  */
  4. #include <iostream>
  5. #include <functional>
  6. #include <vector>
  7. #include <algorithm>
  8.  
  9. typedef std::vector<std::string>::iterator iterator;
  10.  
  11. struct startsWithA : public std::unary_function<std::string, bool> {
  12.     bool operator() (std::string s)
  13.     {
  14.         if(s[0] == 'A')
  15.         {
  16.             return true;
  17.         }
  18.         else
  19.             return false;
  20.     }
  21. };
  22.  
  23. void print(iterator b, iterator e)
  24. {
  25.     iterator i;
  26.     for(i = b; i != e; i++)
  27.     {
  28.         std::cout << *i << "    ";
  29.     }
  30.     std::cout << std::endl;
  31. }
  32.  
  33. int main()
  34. {
  35.     startsWithA s;
  36.     std::vector<std::string> v;
  37.     v.push_back("China");
  38.     v.push_back("India");
  39.     v.push_back("Atlanta");
  40.     v.push_back("Bolivia");
  41.     v.push_back("Australia");
  42.     v.push_back("Pakistan");
  43.  
  44.     std::cout << "Vector : ";
  45.     print(v.begin(), v.end());
  46.     iterator i = remove_if(v.begin(), v.end(), s);
  47.     std::cout << "Vector : ";
  48.     print(v.begin(), i);
  49. }

$ a.out
Vector : China    India    Atlanta    Bolivia    Australia    Pakistan    
Remove countries starting with 'A'  
Vector : China    India    Bolivia    Pakistan

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
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.