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.

advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification 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
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.