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.
/*
* C++ Program to Demonstrate erase() Function on Vectors
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
template <class T>
void print(const std::vector <T>& v)
{
typename std::vector <T>::const_iterator i;
std::cout << "Vector v : " << std::endl;
for(i = v.begin(); i != v.end(); i++)
{
std::cout << (i - v.begin() + 1)
<< ". " << *i << std::endl;
}
}
int main()
{
std::vector <std::string> country;
country.push_back("China");
country.push_back("Germany");
country.push_back("India");
country.push_back("Pakistan");
country.push_back("Russia");
country.push_back("USA");
print(country);
country.erase(country.begin() + 2, country.end() - 2);
std::cout << "After country.erase(country.begin() + 2,"
<< "country.end() - 2) " << std::endl;
print(country);
}
$ 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.
Related Posts:
- Practice Computer Science MCQs
- Apply for C++ Internship
- Check Computer Science Books
- Apply for Computer Science Internship
- Check C++ Books