#include <iostream>
#include <vector>
usingnamespace std;
int main()
{
vector<int> v;
for(int i = 1;i <= 10;i++)
{
v.push_back(i);
}
int beg = 0;
int end = v.size() - 1;
for(int i = end;i >= beg;i--)
{ //remove 5 and also remove something other number
if(v[i] == 5)
{
//remove 5 and 3 at same time
v.erase(v.begin()+i);
v.erase(v.begin()+2); // i remove 3 but 2 is a literal which i dont want to use
}
}
for(int i = 0; i < v.size();i++)
{
cout << v[i] << " ";
}
return 0;
}
That is not exactly "remove 5 and 3 at same time".
It is more like:
IF there is element with value 5
THEN remove that element and the third element of the vector
Furthermore, the "if there is" seeks the vector in reverse order.
You do already have two issues:
* If the last element has value 5, then the vector shrinks by two elements, but the 'i' only by one. Next iteration does thus v[v.size()], which is out of range error.
* What if vector has size 3 and the last value is 5? After erasing that you try to erase the third element of size 2 vector. Out of range error.
You do probably have some reason to erase the third element. The third element is literally the third, there is no way around that. Are you just trying to avoid some other problem with the "without literals" idea?
#include <iostream>
#include <vector>
usingnamespace std;
int main()
{
vector<int> v;
for(int i = 1;i <= 10;i++)
{
v.push_back(i);
}
int beg = 0;
int end = v.size() - 1;
for(int i = end;i >= beg;i--)
{ //remove 5 and also remove something other number
if(v[i] == 5 || v[i] == 3)
{
//remove 5 and 3 at same time
v.erase(v.begin() + i);
i = v.size() - 1; //restart the loop
}
}
for(int i = 0; i < v.size();i++)
{
cout << v[i] << " ";
}
return 0;
}