I wanted to remove vector elements based on the index of, say, all even indexed elements. I read about erasing the removal of an idiom, but don’t see how to apply it. This is what I tried:
vector<int> line;
line.reserve(10);
for(int i=0;i<10;++i)
{
line.push_back(i+1);
}
for(unsigned int i=0;i<line.size();++i)
{
if(i%2 == 0)
{
remove(line.begin(),line.end(),line[i]);
}
}
line.erase( line.begin(),line.end() );
This erases the entire vector. I was hoping to remove only those items that were marked by the delete algorithm.
Then i tried this
for(unsigned int i=0;i<line.size();++i)
{
if(i%2 == 0)
{
line.erase( remove(line.begin(),line.end(),line[i]),line.end() );
}
}
This does not work again, since removing the problem causes a problem, the indexes seem to shift, iterating over the vector. What should be the right approach to achieve this.
source
share