使用迭代器行走和不行走std :: vector的最干净方法是什么? [英] What's the cleanest way to walk and unwalk a std::vector using iterators?
问题描述
我遇到了通过矢量行进的情况:
I have a situation where I'm marching through a vector, doing things:
std::vector::iterator iter = my_list.begin();
for ( ; iter != my_list.end(); ++iter )
{
if ( iter->doStuff() ) // returns true if successful, false o/w
{
// Keep going...
}
else
{
for ( ; iter != m_list.begin(); --iter ) // ...This won't work...
{
iter->undoStuff();
}
}
}
在正常情况下-假设一切顺利-我一路前进到my_list.end()
并成功结束循环.
Under normal conditions - assuming everything goes well - I march all the way to my_list.end()
and end the loop successfully.
但是,如果我在做某事时出了点问题,我希望能够撤消所有操作-基本上将步退回到向量的最开始,以相反的顺序一次撤消所有操作.
However, if something goes wrong while I'm doing stuff, I want to be able to undo everything - basically retrace my steps back to the very beginning of the vector, undoing everything one at a time in reverse order.
我的问题是,当我进入my_list.begin()
时(如嵌套的for循环所示),我真的还没有完成,因为我仍然需要在列表中的第一个元素上调用undoStuff()
.现在,我可以在循环外进行最终调用,但这似乎有点不干净.
My problem is that when I get to my_list.begin()
- as shown in the nested for loop - I'm really not done yet because I still need to call undoStuff()
on my first element in the list. Now, I could just make the final call outside of the loop, but this seems a little unclean.
我所看到的方式,只有到my_list.rend()
时我才能完成.但是,我无法将std :: vector :: iterator与std :: vector :: reverse_iterator进行比较.
The way I see it, I'm only done when I get to my_list.rend()
. However, I can't compare a std::vector::iterator to a std::vector::reverse_iterator.
鉴于我要做什么,迭代器类型/循环组合的最佳选择是什么?
Given what I'm trying to do, what's the best choice of iterator-type / loop combination?
推荐答案
虽然通过rbegin()
和rend()
使用反向迭代器效果很好,但不幸的是,我发现在反向和非反向iterarotr之间进行转换往往会造成混乱.我永远都记不记得是否需要在转换之前或之后进行递增或递减的逻辑难题练习.因此,我通常避免转换.
While using reverse iterators via rbegin()
and rend()
works nicely, unfortunately I find that converting between reverse and non-reverse iterarotrs tends to be quite confusing. I can never remember without having to go through a logic-puzzle exercise whether I need to increment or decrement before or after the conversion. As a result I generally avoid the conversion.
这是我可能对您的错误处理循环进行编码的方式.请注意,我认为您不必为失败的迭代器调用undoStuff()
-毕竟,doStuff()
说它没有成功.
Here's the way I'd probably code your error handling loop. Note that I'd think that you wouldn't have to call undoStuff()
for the iterator that failed - after all, doStuff()
said it didn't succeed.
// handle the situation where `doStuff() failed...
// presumably you don't need to `undoStuff()` for the iterator that failed
// if you do, I'd just add it right here before the loop:
//
// iter->undoStuff();
while (iter != m_list.begin()) {
--iter;
iter->undoStuff();
}
这篇关于使用迭代器行走和不行走std :: vector的最干净方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!