为什么在迭代该向量时会出现分段错误?
我需要遍历这个向量并删除重复项。这段代码中的某个地方发生了分段错误。我的猜测是,它与迭代器运行时删除元素有关,但我还没有真正了解这些迭代器的实际工作原理,所以我无法弄清楚。
vector<char *>::iterator iter;
for (iter = v->begin(); iter != v->end()-1; iter++ ){
char *aString = *iter;
int n = 1;
while(iter+n != v->end()){
int comparison = strcmp(aString, *(iter+n));
if(comparison == 0){
v->erase(iter + n);
}
n++;
}
}
I need to go through this vector and delete the duplicates. A segmentation fault is occurring somewhere within this code. My guess is that it has something to do with deleting elements while the iterator is going through, but I don't really have a concrete understanding of how these iterators are actually working yet, so I can't figure it out.
vector<char *>::iterator iter;
for (iter = v->begin(); iter != v->end()-1; iter++ ){
char *aString = *iter;
int n = 1;
while(iter+n != v->end()){
int comparison = strcmp(aString, *(iter+n));
if(comparison == 0){
v->erase(iter + n);
}
n++;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
确实,这里只是遇到了几个一对一的问题。当您删除一个元素时,您与
end()
进行了错误的比较并递增了n
:下面
将执行您想要的操作(并证明它有效):
输出是:
Really, you just have a couple off-by-one problems here. You were comparing incorrectly against
end()
and incrementingn
when you erased an element:And
The following will do what you want (and demonstrate that it works):
Output is:
您没有正确迭代向量的其余部分。 Beta 建议的另一种方法是将擦除删除与remove_if 结合使用。像这样:
You are not properly iterating through the remainder of the vector. An alternative to what Beta suggested is to use erase-remove with remove_if. Like this:
当您从向量中删除一个元素时,向量会缩短一个元素。试试这个:
When you erase an element from the vector, the vector gets one element shorter. Try this:
从向量中擦除会使从擦除开始的所有迭代器无效,因此您可能不应该按照您的方式构建循环,而应该使用如下标准习惯用法:
此代码避免了对空向量的检查,您的代码无法考虑到空向量为了。
Erasing from a vector invalidates all iterators from the erasee onwards, so you should probably not construct your loop the way you do, and rather use a standard idiom like this:
This code avoids the check for an empty vector, which your code fails to account for.