删除矢量中的字符串

Delete strings in a vector

本文关键字:字符串 删除      更新时间:2023-10-16

我有一个充满字符串的向量

向量一致性Words包含4个字符串

  1. dedf
  2. eedf
  3. 联邦调查局
  4. hedf

现在我想删除所有单词不是以字母d 开头的字符串

然而,它最终只是删除了eedf和hedf,我留下的结果是

  1. dedf
  2. 联邦调查局

我的代码:

    for(int q=0; q<consistentWords.size(); q++)
    {
        string theCurrentWord = consistentWords[q];
        if(theCurrentWord[0] != 'd')
        {
            consistentWords.erase(consistentWords.begin()+q);
        }
    }

有什么想法吗?我只是不明白为什么它没有删除所有不是以d开头的字符串。

首先,字符串对应于以下索引:

dedf 0
eedf 1
fedf 2
hedf 3

假设你删除了eedf(所以q == 1。删除后,向量看起来像

dedf 0
fedf 1
hedf 2

但随后q增加到2,完全跳过fedf。修复方法是稍微改变for循环:

for(int q=0; q<consistentWords.size();)
{
    string theCurrentWord = consistentWords[q];
    if(theCurrentWord[0] != 'd')
    {
        consistentWords.erase(consistentWords.begin()+q);
    }
    else
    {
        q++;
    }
}

或者类似的东西。

您正在跳过元素。假设您需要删除元素5,6:当你删除元素5时,元素6变成了元素5,你跳过它,因为q增加到了6,

更好的方法是手动增加q,仅当您不删除元素

问题是在同一迭代中从向量中删除元素并递增索引q。因此,在for循环的第二次迭代中,从向量中删除"eedf",那么向量就是["dedf", "fedf", "hedf"]q = 1。但是,当您循环回到for循环的开始时,q会增加到2,因此接下来将查看"hedf",跳过"fedf"。要解决此问题,您可以在从数组中删除元素时递减q,如下所示:

for(int q=0; q<consistentWords.size(); q++)
{
    string theCurrentWord = consistentWords[q];
    if(theCurrentWord[0] != 'd')
    {
        consistentWords.erase(consistentWords.begin()+q);
        --q;
    }
}

或者你可以使用迭代器:

vector<string>::iterator it = consistentWords.begin()
while(it != consistentWord.end())
{
    string theCurrentWord = consistentWords[q];
    if(theCurrentWord[0] != 'd')
    {
        it = consistentWords.erase(it);
    }
    else
    {
        ++it;
    }
}

请注意,erase将迭代器返回到您已擦除的元素之后的元素。您必须重新指定it,因为当调整向量大小时,它将变为无效。

擦除时不应执行q++。那么你就错过了一个元素。

这个问题已经得到了回答,但您应该研究擦除删除习惯用法:

示例:

consistentWords.erase(
    std::remove_if(consistentWords.begin(), consistentWords.end(), 
    [](const std::string& s) -> bool { return (s[0] == 'd'); }),
    consistentWords.end());

删除单词:

consistentWords.erase(
    std::remove(consistentWords.begin(), consistentWords.end(), theCurrentWord),
    consistentWords.end()
);