删除向量中的字符串 [英] Delete strings in a vector
问题描述
我有一个充满字符串的向量
I have a vector full of strings
向量consistentWords包含4个字符串
the vector consistentWords contains 4 strings
- def
- edf
- fedf
- hedf
现在我想删除所有不以字母 d 开头的字符串
Now I want to delete all the strings that words don't start with the letter d
然而它最终只是删除了 eedf 和 hedf 而我留下的结果是
However it ends up just deleting eedf and hedf and the result I have left is
- def
- fedf
我的代码:
for(int q=0; q<consistentWords.size(); q++)
{
string theCurrentWord = consistentWords[q];
if(theCurrentWord[0] != 'd')
{
consistentWords.erase(consistentWords.begin()+q);
}
}
有什么想法吗?我只是不明白为什么不删除所有不以 d 开头的字符串.
Any thoughts? I just can't see why it's not deleting all of the strings that don't start with d.
推荐答案
问题是您在同一次迭代中从向量中删除元素并增加索引 q
.所以在你的 for 循环的第二次迭代中,你从你的向量中删除 "eedf"
然后你的向量是 ["dedf", "fedf", "hedf"]
和q = 1
.但是当您循环回到 for 循环的开头时,q
增加到 2,因此您接下来查看 "hedf"
,跳过 "fedf"代码>.要解决此问题,您可以在从数组中删除元素时减少
q
,如下所示:
The problem is you are deleting elements from the vector and incrementing your index q
in the same iteration. So in the 2nd iteration of your for loop, you erase "eedf"
from you vector then your vector is ["dedf", "fedf", "hedf"]
and q = 1
. But then when you loop back to the begining of the for loop, q
is incremented to 2 so you look at "hedf"
next, skipping "fedf"
. To fix this you could decrement q
when you remove an element from the array like so:
for(int q=0; q<consistentWords.size(); q++)
{
string theCurrentWord = consistentWords[q];
if(theCurrentWord[0] != 'd')
{
consistentWords.erase(consistentWords.begin()+q);
--q;
}
}
或者你可以使用迭代器:
Or you could use iterators:
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
因为当向量调整大小时它变得无效.
Note that erase
returns an iterator to the element after the one you have erased. You must re-assign it
because it becomes invalidated when the vector is resized.
这篇关于删除向量中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!