0

I am having trouble deleting certain indexes from a vector type string I have. My task is to fill a vector with html tags (html, head, etc.), but I need to get rid of tags that have no match (assume only p, br, img). Everytime I print the vector after the for loop, I get a stray br and p. Help would be much appreciated!

    for (int i = 0; i < tagStorage.size(); i++) {

    if (tagStorage[i].find_first_of('/') == true) { //searches for closing tags
        closingTags.push_back(tagStorage[i]);
    }
    else if (tagStorage[i].find("<p>") != string::npos) { //searches for <p> tag
        noMatch.push_back(tagStorage[i]);
        tagStorage.erase(tagStorage.begin() + i); //erase tag
    }
    else if (tagStorage[i].find("<br>") != string::npos) { //searches for <br> tag
        noMatch.push_back(tagStorage[i]);
        tagStorage.erase(tagStorage.begin() + i); //erase tag
    }
    else if (tagStorage[i].find("<img") != string::npos) { //searches for <img ..> tag
        noMatch.push_back(tagStorage[i]);
        tagStorage.erase(tagStorage.begin() + i); //erase tag
    }
    else {
        openingTags.push_back(tagStorage[i]);
    }
}
XZ6H
  • 1,779
  • 19
  • 25
Derek H
  • 31
  • 7

1 Answers1

2

You're iterating past the next expected tagStorage element after removing the current one.

As an example, say you want to remove every 'l' from "Hello!"

"Hello!"
 ^

i++

"Hello!"
  ^

i++

"Hello!"
   ^

Remove 'l'.

i++

"Helo!"
    ^

As you can see, the iteration after removing 'l' goes right past the next character. A solution would be to decrement i after removing an element so that it compensates for the for-loops incrementation.

ben
  • 96
  • 2