简体   繁体   English

反向遍历:迭代器还是反向迭代器:正确性和偏好?

[英]reverse traversal: iterator or reverse iterator: correctness and preference?

Can I reverse traversal using iterator like below (is it correct?): 我可以使用下面的迭代器反转遍历吗(正确吗?):

for (auto it=foo.end()-1; it != foo.begin()-1; it--)
    DoSomethingHere(it);

I have been doing this OK on vectors. 我一直在矢量上做到这一点。 However, from Dr. Dobbs article , it seems that the iterator implementation may vary. 但是,从Dobbs博士的文章看来,迭代器的实现可能有所不同。 I am afraid that it could fail on iterators of other classes. 恐怕它可能在其他类的迭代器上失败。

If the above implementation is correct, is it preferred or is the following reverse-iterator is preferred: 如果以上实现是正确的,则首选还是以下反向迭代器:

for (auto it = foo.rbegin(); it != foo.rend(); it++)
        DoSomethingHere(it);

Related articles/Q&A for this question of preference can be found in: 有关此偏爱问题的相关文章/问答,请参见:

  1. How do you erase AND CONTINUE using a std::reverse_iterator? 如何使用std :: reverse_iterator擦除并继续
  2. Dr. Dobbs article 多布斯博士文章
  3. "What are the shortcomings of std::reverse_iterator?" “ std :: reverse_iterator的缺点是什么?”

foo.begin()-1 produces undefined behavior, so no, it's not a good idea. foo.begin()-1产生未定义的行为,所以不,这不是一个好主意。

Given that you're doing exactly what a reverse iterator is designed to accomplish, it seems like the obvious way to do things. 既然你在做什么一个反向迭代器被设计来完成,这似乎是明显的方式来做事。 There are certainly limitations on reverse iterators, but for many situations (including what you've outlined above) they're simply irrelevant. 反向迭代器当然有局限性,但是在许多情况下(包括上面概述的情况),它们根本无关紧要。

As an aside, your second loop is basically equivalent to: 顺便说一句,您的第二个循环基本上等效于:

std::for_each(foo.rbegin(), r.rend(), DoSomethinghere);

Other than the (usually irrelevant) detail that for_each will pass the item the iterator points at, rather than the iterator itself. 除了for_each将传递迭代器指向的项目(通常不相关)的细节(而不是迭代器本身)之外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM