Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete strings in a vector

Tags:

c++

string

vector

I have a vector full of strings

the vector consistentWords contains 4 strings

  1. dedf
  2. eedf
  3. fedf
  4. hedf

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

  1. dedf
  2. fedf

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.

like image 316
Claud Avatar asked Mar 09 '26 07:03

Claud


2 Answers

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.

like image 178
Ken Wayne VanderLinde Avatar answered Mar 11 '26 19:03

Ken Wayne VanderLinde


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

like image 24
amit Avatar answered Mar 11 '26 20:03

amit