C++ 迭代时删除
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3901356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
deleting while iterating
提问by nacho4d
Possible Duplicates:
Vector.erase(Iterator) causes bad memory access
iterate vector, remove certain items as I go.
Hi, I wrote this but I am get some errors when running it
嗨,我写了这个,但运行它时出现一些错误
for (vector< vector<Point> >::iterator track = tracks_.begin(); track != tracks_.end(); track++) {
if (track->empty()) { // if track is empty, remove it
tracks_.erase(track);
track++; // is this ok?
}else { //if there are points, deque
track->erase(track->begin()); //my program crashes here after a while... ;(
}
}
I have a vector of vector of points (2 ints) whose I call tracks (1 track is 1 vector of points) I want to check each track and if they contain points then delete the first one otherwise delete the track. Is this correct?
我有一个点向量向量(2个整数),我称之为轨道(1个轨道是1个点向量)我想检查每个轨道,如果它们包含点,则删除第一个,否则删除轨道。这样对吗?
Thanks in advance.
提前致谢。
回答by sth
A vector's erase()
invalidates existing iterators, but it returnsa new iterator pointing to the element after the one that was removed. This returned iterator can be used to continue iterating over the vector.
向量erase()
会使现有的迭代器失效,但它返回一个新的迭代器,该迭代器指向被删除的元素之后的元素。这个返回的迭代器可用于继续迭代向量。
Your loop could be written like this:
你的循环可以这样写:
vector< vector<Point> >::iterator track = tracks_.begin();
while (track != tracks_.end()) {
if (track->empty()) {
// if track is empty, remove it
track = tracks_.erase(track);
}
else {
//if there are points, deque
track->erase(track->begin());
++track;
}
}
回答by David Titarenco
I'm not sure what errors you're getting, but chances are that you're invalidating your iterator.
我不确定您遇到了什么错误,但很可能您使迭代器无效。
You should read http://www.angelikalanger.com/Conferences/Slides/CppInvalidIterators-DevConnections-2002.pdf
您应该阅读http://www.angelikalanger.com/Conferences/Slides/CppInvalidIterators-DevConnections-2002.pdf
Specifically, vector::erase
invalidates all iterator and references to elements after position or first.
具体来说,vector::erase
使所有迭代器和对 position 或 first 之后元素的引用无效。