c++ - 使用常规迭代器向后迭代,还是与 reverse_iterator 斗争?

标签 c++ stl iterator

我最近了解了在 C++ 中使用反向迭代器的正确方法(特别是当您需要删除一个时)。 (参见 this questionthis 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 指出的那样):

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

缺点:

  • 你告诉我。有什么问题吗?
  • 正如 MooingDuck 指出的那样,它不符合标准。这几乎否定了以下任何可能的优势。

优点:

  • 对反向 for 循环使用熟悉的习语
  • 不必记住(或解释)+1
  • 减少打字
  • 也适用于 std::list:it = il.erase(it);
  • 如果你删除一个元素,你不必调整迭代器
  • 如果删除,则不必重新计算开始迭代器

最佳答案

反向迭代器的原因是 standard algorithms不知道如何向后迭代集合。例如:

#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)

使用任何一个迭代器都会产生更清晰的代码。

关于c++ - 使用常规迭代器向后迭代,还是与 reverse_iterator 斗争?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1853358/

相关文章:

c++ - std::make_pair 与 std::pair 的构造函数的目的是什么?

c++ - C++ vector 的 size() 和 capacity()

python 3.x : Subtract Same Index from Sequential Lines

java - 如何保护列表中列表的旧位置以将其替换为新位置

C++ 虚拟构造函数,没有 clone()

java - C++:使用抽象方法创建抽象类并覆盖子类中的方法

c++ - 将 char 数组结构 vector 转换为 POD vector ?

c++ - std::list 的 const_iterator 与迭代器

c++ - 汽车有什么用?

c++ - 使用临时字符串构建 istringstream