使用常规迭代器向后迭代,或使用reverse_iterator? [英] Use a regular iterator to iterate backwards, or struggle with reverse_iterator?

查看:142
本文介绍了使用常规迭代器向后迭代,或使用reverse_iterator?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近学到了使用C ++中的反向迭代器的正确方法(特别是当你需要删除一个时)。 (请参见此问题这一个。)

I recently learned about the right way to work with reverse iterators in C++ (specifically when you need to erase one). (See this question and this one.)

这是你应该做的:

typedef std::vector<int> IV;
for (IV::reverse_iterator rit = iv.rbegin(), rend = iv.rend();
     rit != rend; ++rit)
{
  // Use 'rit' if a reverse_iterator is good enough, e.g.,
  *rit += 10;
  // Use (rit + 1).base() if you need a regular iterator e.g.,
  iv.erase((rit + 1).base());
}

但是我认为 不要这样做,不符合标准,正如MooingDuck指出的):

But I think thought this is much better (Don't do this, not standards compliant, as MooingDuck points out):

for (IV::iterator it = iv.end(), begin = iv.begin();
     it-- != begin; )
{
  // Use 'it' for anything you want
  *it += 10;
  iv.erase(it);
}

缺点:


  • 你告诉我。发生了什么问题?

  • 这是不符合标准的,因为MooingDuck点出来。

  • You tell me. What's wrong with it?
  • It's not standards compliant, as MooingDuck points out. That pretty much overrules any of the possible advantages below.

优点:


  • 使用熟悉的惯用法用于反向for-loops

  • 不必记住(或解释) +1

  • 减少键入

  • 适用于std :: list: it = il.erase ;

  • 如果您删除元素,则不必调整迭代器。

  • 不必重新计算begin迭代器

  • Uses a familiar idiom for reverse for-loops
  • Don't have to remember (or explain) the +1
  • Less typing
  • Works for std::list too: it = il.erase(it);
  • If you erase an element, you don't have to adjust the iterator
  • If you erase, you don't have to recompute the begin iterator

推荐答案

反向迭代器的原因是标准算法不知道如何对集合进行反向迭代。例如:

The reason for reverse iterators is that the standard algorithms do not know how to iterate over a collection backwards. For example:

#include <string>
#include <algorithm>
std::wstring foo(L"This is a test, with two letter a's involved.");
std::find(foo.begin(), foo.end(), L'a'); // Returns an iterator pointing
                                        // to the first a character.
std::find(foo.rbegin(), foo.rend(), L'a').base()-1; //Returns an iterator
                                                 // pointing to the last A.
std::find(foo.end(), foo.begin(), L'a'); //WRONG!! (Buffer overrun)

使用任何迭代器产生更清晰的代码。

Use whichever iterator results in clearer code.

这篇关于使用常规迭代器向后迭代,或使用reverse_iterator?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆