【问题标题】:Deleting an element of a vector at a specific index删除特定索引处的向量元素
【发布时间】:2017-03-23 04:17:27
【问题描述】:

我无法从我拥有的向量类型字符串中删除某些索引。我的任务是用 html 标签(html、head 等)填充向量,但我需要去掉不匹配的标签(假设只有 p、br、img)。每次我在 for 循环之后打印向量时,我都会得到一个杂散的 br 和 p。非常感谢您的帮助!

    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]);
    }
}

【问题讨论】:

标签: c++ loops vector indexing


【解决方案1】:

在删除当前元素后,您正在迭代下一个预期的 tagStorage 元素。

例如,假设您想从“Hello!”中删除每个“l”

"Hello!"
 ^

我++

"Hello!"
  ^

我++

"Hello!"
   ^

删除“l”。

我++

"Helo!"
    ^

如您所见,删除 'l' 后的迭代正好经过下一个字符。一个解决方案是在删除一个元素后减少 i,以便它补偿 for 循环的增量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-26
    • 2015-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-18
    • 2011-04-16
    • 1970-01-01
    相关资源
    最近更新 更多