remove() Function in C++
Posted by Superadmin on August 10 2022 05:32:49

remove() Function in C++

 

This C++ program demonstrates the remove() algorithm. The program creates a vector of strings and removes an element using the remove algorithm from the algorithm library.

 

Here is the source code of the C++ program which demonstrates the remove() 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 algorithm
  3.  */
  4. #include <iostream>
  5. #include <string>
  6. #include <vector>
  7. #include <algorithm>
  8.  
  9. typedef std::vector <std::string>::iterator iterator;
  10.  
  11. void print(iterator b, iterator e)
  12. {
  13.     iterator i;
  14.     for (i = b; i != e; i++)
  15.     {
  16.         std::cout << *i << "    ";
  17.     }
  18.     std::cout << std::endl;
  19. }
  20.  
  21. int main()
  22. {
  23.     std::vector <std::string> v;
  24.     iterator i;
  25.     v.push_back("China");
  26.     v.push_back("Dubai");
  27.     v.push_back("Boston");
  28.     v.push_back("France");
  29.     v.push_back("Hungary");
  30.     v.push_back("Australia");
  31.  
  32.     std::cout << "Places to visit : ";
  33.     print(v.begin(), v.end());
  34.     i = remove(v.begin(), v.end(), "Boston");
  35.     std::cout << "Visited Boston" << std::endl;
  36.     std::cout << "Places to visit : ";
  37.     print(v.begin(), i);
  38. }

 

$ a.out
Places to visit : China    Dubai    Boston    France    Hungary    Australia    
Visited Boston
Places to visit : China    Dubai    France    Hungary    Australia