2008年10月3日 星期五

vector::erase和iterator的問題

vector::erase後,原本的iterator會失效
所以在使用for-loop + erase要特別注意

help有指出,vector::erase會回傳一個有效的iterator


A random access iterator pointing to the new location of the element that followed the last element erased by the function call, which is the vector end if the operation erased the last element in the sequence.
http://www.cplusplus.com/reference/stl/vector/erase.html




std::vector values;
for (std::vector::iterator it = values.begin(); it != values.end(); )
{
if (*it > 10)
{
it = values.erase(it);
}
else
{
++it;
}
}

2 則留言:

fr3@K 提到...

用 while loop 似乎更為直覺.

另, 請參考 這篇文字 與接續的討論.

高橋旺 提到...

while loop的確直覺點 :)

LinkWithin

Related Posts with Thumbnails