获取 std::list<>::iterator 的值到指针?
我如何循环遍历 stl::List 并存储其中一个对象的值以供稍后在函数中使用?
Particle *closestParticle;
for(list<Particle>::iterator p1 = mParticles.begin(); p1 != mParticles.end(); ++p1 )
{
// Extra stuff removed
closestParticle = p1; // fails to compile (edit from comments)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要么
要么
这些
要么 要么
按照个人喜好递增排序。 <代码>:)
Either
or
or
or
These are sorted in increasing personal preference.
:)
对于
列表
,使迭代器无效的唯一方法是擦除
它。所以我怀疑您在循环中的某个时刻调用list.erase(p1)
。您需要制作迭代器的副本,将p1
移回一位,然后擦除副本。编辑:哦等等,你的意思是它不能编译?如果是这样,请参阅@sbi 的回答。但你确实需要以一种好的方式表达你的问题。你的编译错误是什么?或者它在运行时失败?然而,在这种情况下,我相信你的意思是编译错误。
For a
list
, the only way to invalidate an iterator is toerase
it. So I suspect you're callinglist.erase(p1)
at some point in the loop. You need to make a copy of the iterator, movep1
back one, and then erase the copy.EDIT: Oh wait, did you mean it doesn't compile? If so, see @sbi's answer. But you really need to word your question in a good way. What is your compile error? Or does it fail at run-time? In this case, however, I believe you mean a compile error.