I have a vector full of strings
the vector consistentWords contains 4 strings
Now I want to delete all the strings that words don't start with the letter d
However it ends up just deleting eedf and hedf and the result I have left is
My code:
for(int q=0; q<consistentWords.size(); q++)
{
string theCurrentWord = consistentWords[q];
if(theCurrentWord[0] != 'd')
{
consistentWords.erase(consistentWords.begin()+q);
}
}
Any thoughts? I just can't see why it's not deleting all of the strings that don't start with d.
To start with, the strings correspond to these indices:
dedf 0
eedf 1
fedf 2
hedf 3
Let's say you delete eedf (so q == 1. After the delete, the vector looks like
dedf 0
fedf 1
hedf 2
But then q gets incremented to 2, completely skipping over fedf. The fix would be to alter the for loop slightly:
for(int q=0; q<consistentWords.size();)
{
string theCurrentWord = consistentWords[q];
if(theCurrentWord[0] != 'd')
{
consistentWords.erase(consistentWords.begin()+q);
}
else
{
q++;
}
}
or something to the same effect.
You are skipping elements. Assume you need to delete elements 5,6:
when you delete element 5, element 6 becomes element 5 - and you skip it, since q was increased to 6,
The better way to do it is manually increasing q only when you do not delete an element
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With