//C++ code to demonstrate erase function in vector
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v1(1, 2); // default constructor to assign one element
vector<int>::iterator it = v1.begin();
cout << "v1 initially contains : ";
for (int i = 0; i < v1.size(); ++i)
cout << v1[i] << '\t';
cout << endl;
v1.insert(it + 1, 3, 5); //inserting 3 elements of value 5
cout << "v1 now contains : ";
for (int i = 0; i < v1.size(); ++i)
cout << v1[i] << '\t';
cout << endl;
v1.erase(it + 2, it + 4); // erasing elements in the range
cout << "v1 now contains : ";
for (int i = 0; i < v1.size(); ++i)
cout << v1[i] << '\t';
cout << endl;
return 0;
}
This code is creating a vector and assigning a value of 2 to it. Then it prints it out using the iterator. Next we insert 3 elements in the vector and each of those are 5. Then using iterator I am trying to delete elements between (it +2 and it+4). Then while trying to print the final vector, I am not sure why it is printing 5 5.