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