删除矢量中的字符串
Delete strings in a vector
我有一个充满字符串的向量
向量一致性Words包含4个字符串
- dedf
- eedf
- 联邦调查局
- hedf
现在我想删除所有单词不是以字母d 开头的字符串
然而,它最终只是删除了eedf和hedf,我留下的结果是
- dedf
- 联邦调查局
我的代码:
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()
);
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 如何从给定字符串中删除第二次和第三次出现的$
- 在C++的字符串中搜索和删除某些字符
- 从 C 样式字符串中删除子字符串 "in place" 在C++代码中
- 使用另一个字符串从字符串中删除空格
- 删除/替换C++字符串中的多字符 (ÿû)
- 删除所有字符串后如何恢复 QStringList?
- 如何删除字符串中的前 2 个字符(如果它有"-")
- 根据新的行分隔符从字符串中删除子字符串
- C ++,如何从控制台中输入的字符串中删除字母?
- 删除字符串后C++检测到堆损坏
- 我正在尝试使用 while 循环从字符串中删除字母,直到没有字母。我在这里做错了什么?
- 如何在 c++ 中删除字符串中的某些字符?
- 删除字符串数组
- 删除字符串中具有相同值的任何相邻字母"pair"
- 高效的字符串截断算法,按顺序删除相等的前缀和后缀
- 如何使用双黑斜杠从字符串中删除单反斜杠
- 如何在编译时从string_view中删除子字符串?
- 从文件中读取多行.txt字符串删除空格并创建新文件进行输出
- c字符串 删除非字母/非空格字符 - C++