erase() Function in C++

This C++ program demonstrates erase() function on vectors. The erase function takes iterators to the portion of the container(like list, vector, etc.) to be deleted, i.e. if you pass the iterator to beginning and end of the container, the function will empty that container.

Here is the source code of the C++ program demonstrates erase() function on vectors 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 erase() Function on Vectors
  3.  */ 
  4. #include <iostream>
  5. #include <vector>
  6. #include <algorithm>
  7. #include <string>
  8.  
  9. template <class T>
  10. void print(const std::vector <T>& v)
  11. {
  12.     typename std::vector <T>::const_iterator i;
  13.     std::cout << "Vector v : " << std::endl;
  14.     for(i = v.begin(); i != v.end(); i++)
  15.     {
  16.         std::cout << (i - v.begin() + 1)
  17.                   << ". " << *i << std::endl;
  18.     }
  19. }
  20.  
  21. int main()
  22. {
  23.     std::vector <std::string> country;
  24.     country.push_back("China");
  25.     country.push_back("Germany");
  26.     country.push_back("India");
  27.     country.push_back("Pakistan");
  28.     country.push_back("Russia");
  29.     country.push_back("USA");
  30.  
  31.     print(country);
  32.     country.erase(country.begin() + 2, country.end() - 2);
  33.     std::cout << "After country.erase(country.begin() + 2,"
  34.               << "country.end() - 2) " << std::endl;
  35.     print(country);
  36. }

$ a.out
Vector v :
1. China
2. Germany
3. India
4. Pakistan
5. Russia
6. USA
After country.erase(country.begin() + 2, country.end() - 2)
Vector v :
1. China
2. Germany
3. Russia
4. USA

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

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 & discussions at Telegram SanfoundryClasses.